﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Data.SqlClient;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.Geometry;

//using ESRI.ArcGIS.AnalysisTools;

namespace Tayninh2011
{
    class TnTools:ITnToolsWorkspace,ITnToolsSpatial,ITnToolsTable,ITnToolsCalculator,ITnToolsSpatialRel,ITnToolsDataManager
    {
        protected string _mdbTempFolder ="" ;
        protected string _mdbTempFileName = "";
        private IWorkspaceEdit _sdeWorkspace;
        private string[,] _arrUserInfo;

        protected IFeatureWorkspace _sdeFeatureWorkspace ;
        public TnTools()
        {
            this._mdbTempFolder = "C:\\tayninh\\temp";
            this._mdbTempFileName = "tempmdb";
        }
        protected IWorkspaceEdit SdeWorkspace
        {
            get { return _sdeWorkspace; }
            set { _sdeWorkspace = value; }
        }
        public TnTools(string tempPath)
        {
            this._mdbTempFolder = tempPath;
            
        }
        public TnTools(IWorkspaceEdit workspace)
        {
            this.SdeWorkspace = workspace;
            this._sdeFeatureWorkspace = (IFeatureWorkspace)workspace;
        }
        public string[,] ArrUserInfo
        {
            get { return _arrUserInfo; }
            set { _arrUserInfo = value; }
        }
        #region ITnToolsWorkspace Members

        IWorkspace ITnToolsWorkspace.CreateWorkspaceGdbFile(string path, string name, string type)
        {
            try
            {
                IWorkspace wp;
                IWorkspaceName wpn;
                IName nwp;
                IWorkspaceFactory2 wspf;
                Directory.CreateDirectory(path);
                path = path + "\\";
                switch (type)
                {
                    case "mdb":
                        wspf = new AccessWorkspaceFactoryClass();
                        name = name + ".mdb";
                        break;
                    case "shp":
                        wspf = new ShapefileWorkspaceFactoryClass();
                        break;
                    default:
                        wspf = new ShapefileWorkspaceFactoryClass();
                        break;
                }
                wpn = wspf.Create(path, name, null, 0);
                nwp = (IName)wpn;
                wp = (IWorkspace)nwp.Open();
                return wp;
            }
            catch { return null; }

        }

        IFeatureClass ITnToolsWorkspace.OpenFeatureClassFromFileMdb(string path, string name)
        {
            IWorkspaceFactory2 mdbWspf = new AccessWorkspaceFactoryClass();
            IWorkspace wsp;
            IFeatureWorkspace fwsp;

            wsp = mdbWspf.OpenFromFile(path, 0);
            fwsp = (IFeatureWorkspace)wsp;
            return fwsp.OpenFeatureClass(name);
        }

       IWorkspaceEdit ITnToolsWorkspace.CreateWorkspaceSDE(string server, string instance, string authentication_mode, string database, string version, string user, string password)
        {
            IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass();
            IPropertySet propertySet = new PropertySetClass();
            //create version for editting
            TnUtilities utilities = new TnUtilities();
            IWorkspaceEdit workspaceEdit = null;
            //utilities.StartService("esri_sde", 2000);

            propertySet.SetProperty("SERVER", server);
            propertySet.SetProperty("INSTANCE", instance);
            propertySet.SetProperty("DATABASE", database);

            propertySet.SetProperty("VERSION", version);
            if (authentication_mode != "OSA" && authentication_mode != "osa")
            {
                propertySet.SetProperty("USER", user);
                propertySet.SetProperty("PASSWORD", password);
            }
            else if (authentication_mode == "OSA" || authentication_mode == "osa")
            {
                propertySet.SetProperty("AUTHENTICATION_MODE", authentication_mode);
            }
            else
            {
                MessageBox.Show("Chua xac dinh duoc Authentication_mode");
            }
            //if (version == "sde.DEFAULT")
            //{
            //    Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
            //    workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
            //}
            if (version == "dbo.DEFAULT")
            {
                propertySet.SetProperty("VERSION", version);
            }
            else
            {
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
                workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
            }

            workspaceEdit = (IWorkspaceEdit)workspaceFactory.Open(propertySet, 0);
            if (workspaceEdit.IsBeingEdited() != true)
            {
                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();
            }
            return workspaceEdit;
        }
        IFeatureClass ITnToolsWorkspace.OpenFeatureClassFromSDE(IWorkspaceEdit workspace,string featureClass)
        {
            //--
            IFeatureWorkspace fwsp = (IFeatureWorkspace)workspace;
            return fwsp.OpenFeatureClass(featureClass);
            //throw new NotImplementedException();
        }

        //kiem tra 1 layer da co trong csdl hay chua
        bool ITnToolsWorkspace.CheckLayerExist(string[,] user_info, string layer_name)
        {
            string strConnection = "";
            string sql = "SELECT * FROM sde.sde.SDE_table_registry WHERE table_name='" + layer_name + "'";

            for (int i = 0; i < user_info.Length / 2; i++)
            {
                strConnection += user_info[i, 0] + "=" + user_info[i, 1];
                strConnection += ";";
            }
            SqlConnection conn = new SqlConnection(strConnection);
            SqlCommand cmd = new SqlCommand(sql, conn);
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            int a = 0;
            while (reader.Read())
            {
                a++;
            }
            if (reader.HasRows)
            {
                //MessageBox.Show(a.ToString());
                return true;
            }
            else
            {
                //MessageBox.Show(reader.HasRows.ToString());
                return false;
            }
        }
        #endregion //ITnToolsWorkspace

        #region ITnToolsSpatial Members

        IFeatureClass ITnToolsSpatial.TnBuffer(string in_features, string out_feature, object distance, string environment,IWorkspaceEdit workspace)
        {
            IFeatureClass bufferFeatureClass;
            //IWorkspaceFactory2 shpWspf = new ShapefileWorkspaceFactoryClass();
            IWorkspaceFactory2 mdbWspf = new AccessWorkspaceFactoryClass();
            IWorkspace wsp;
            IFeatureWorkspace fwsp;
            //IFeatureLayer fl;
            ITnToolsWorkspace workspaceTool = new TnTools();
            TnUtilities tnUti=new TnUtilities();
            Geoprocessor gp = new Geoprocessor();
            char[] charSplit={'\\'};
            string out_feature_name=tnUti.GetNameFromPathIncludeDot(out_feature,charSplit);
            ESRI.ArcGIS.AnalysisTools.Buffer bufferTool = new ESRI.ArcGIS.AnalysisTools.Buffer();

            gp.SetEnvironmentValue("workspace", environment);
            bufferTool.in_features = in_features;
            bufferTool.out_feature_class =out_feature;//"Database Connections/Connection to ht_laptop.sde"+out_feature;//
            bufferTool.buffer_distance_or_field = distance;

            gp.Execute(bufferTool, null);
            //bufferFeatureClass = workspaceTool.OpenFeatureClassFromSDE(workspace, out_feature);
            bufferFeatureClass = workspaceTool.OpenFeatureClassFromFileMdb(tnUti.GetPathWithoutName(out_feature, charSplit), out_feature_name);
            //wsp = mdbWspf.OpenFromFile(out_feature, 0);
            //fwsp = (IFeatureWorkspace)wsp;
            //bufferFeatureClass = fwsp.OpenFeatureClass(out_feature);


            return bufferFeatureClass;
        }

        void ITnToolsSpatial.TnBufferInsideSde(string in_features, string out_feature, object distance, string environment, IWorkspaceEdit workspace)
        {
            try
            {
                //IFeatureClass bufferFeatureClass;
                //IWorkspaceFactory2 shpWspf = new ShapefileWorkspaceFactoryClass();
                //IWorkspaceFactory2 mdbWspf = new AccessWorkspaceFactoryClass();
                //IWorkspaceEdit wsp;
                //IFeatureWorkspace fwsp;
                //IFeatureLayer fl;
                //ITnToolsWorkspace workspaceTool = new TnTools();
                //TnUtilities tnUti = new TnUtilities();
                Geoprocessor gp = new Geoprocessor();
                //char[] charSplit = { '\\' };
                //string out_feature_name = tnUti.GetNameFromPathIncludeDot(out_feature, charSplit);
                ESRI.ArcGIS.AnalysisTools.Buffer bufferTool = new ESRI.ArcGIS.AnalysisTools.Buffer();

                gp.SetEnvironmentValue("workspace", environment);
                bufferTool.in_features = in_features;
                bufferTool.out_feature_class = out_feature;
                bufferTool.buffer_distance_or_field = distance;
                RunTool(gp, bufferTool, null);
            }
            catch (Exception err) { MessageBox.Show("loi buffer: " + err.ToString()); }
            //gp.Execute(bufferTool, null);
            //bufferFeatureClass = workspaceTool.OpenFeatureClassFromSDE(workspace, "p2_duong");
            //bufferFeatureClass = workspaceTool.OpenFeatureClassFromFileMdb(tnUti.GetPathWithoutName(out_feature, charSplit), out_feature_name);
            //wsp = mdbWspf.OpenFromFile(out_feature, 0);
            //fwsp = (IFeatureWorkspace)wsp;
            //bufferFeatureClass = fwsp.OpenFeatureClass(out_feature);


            //return bufferFeatureClass;
        }

        void ITnToolsSpatial.TnClipInsideSde(ref IFeatureClass in_feature,string clip_feature, string out_feature, string environment)
        {
            //MessageBox.Show(in_feature.Name);
            //tao workspace in-memory
            IWorkspaceFactory im_wspf = new InMemoryWorkspaceFactoryClass();
            IName name = im_wspf.Create("", "tayninh", null, 0) as IName;
            IWorkspace im_wsp = (IWorkspace)name.Open();
            IFeatureWorkspace im_fwsp = (IFeatureWorkspace)im_wsp;
            UID cluid=new UIDClass();
            cluid.Value="esriGeoDatabase.Feature";
            
            //IFeatureClass fc = im_fwsp.CreateFeatureClass("tui", in_feature.Fields, cluid, null, esriFeatureType.esriFTSimple, in_feature.ShapeFieldName,null);
            //MessageBox.Show(fc.FeatureCount(null).ToString());
            Geoprocessor gp = new Geoprocessor();
            ESRI.ArcGIS.AnalysisTools.Clip clipTool = new ESRI.ArcGIS.AnalysisTools.Clip();
            IVariantArray param = new VarArrayClass();
            gp.SetEnvironmentValue("workspace", environment);
            clipTool.in_features = "tn_thua";
            clipTool.clip_features = clip_feature;
            clipTool.out_feature_class = "C:\\tayninh\\temp\\tempmdb.mdb\\" + out_feature;
            
            RunTool(gp, clipTool,null);
        }

        void ITnToolsSpatial.TnIntersectSelection(string in_feature, string select_feature, string environment, IWorkspaceEdit workspace, DataGridView dataGridView)
        {
            //ITnToolsWorkspace wspTool = new TnTools();
            IFeatureClass out_featureClass;
            IQueryFilter qf;
            
            IFeatureClass in_featureClass;
            IFeatureClass select_featureClass;
            IFeatureLayer in_featureLayer=new FeatureLayer();
            IFeatureLayer select_featureLayer = new FeatureLayer();
            in_featureClass = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, in_feature);
            select_featureClass = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, select_feature);
            in_featureLayer.FeatureClass = in_featureClass;
            in_featureLayer.Name = in_featureClass.AliasName;
            select_featureLayer.FeatureClass = select_featureClass;
            select_featureLayer.Name = select_featureClass.AliasName;

            ESRI.ArcGIS.DataManagementTools.MakeFeatureLayer makeLayerTool = new ESRI.ArcGIS.DataManagementTools.MakeFeatureLayer();
            makeLayerTool.in_features = in_feature;
            makeLayerTool.out_layer = "gt_lyr";//_mdbTempFolder + "\\"+_mdbTempFileName+".mdb\\" + out_feature;
            Geoprocessor gp = new Geoprocessor();
            
            gp.SetEnvironmentValue("workspace",environment);
            //gp.Execute(makeLayerTool, null);
            ESRI.ArcGIS.DataManagementTools.SelectLayerByLocation selectTool = new ESRI.ArcGIS.DataManagementTools.SelectLayerByLocation();
            selectTool.in_layer = in_featureLayer;
            //selectTool.out_layer_or_view = out_feature; //_mdbTempFolder + "\\" + _mdbTempFileName + ".mdb\\" + out_feature;
            selectTool.overlap_type="INTERSECT";
            //selectTool.search_distance = "50";
            selectTool.select_features = select_featureLayer;
            selectTool.selection_type = "NEW_SELECTION";
            
            IWorkspaceEdit wsp;
            IFeatureWorkspace fwsp;
            //in_layer=wsp.o
            IGeoProcessorResult result = (IGeoProcessorResult)gp.Execute(selectTool, null);
            IGPUtilities gpu = new GPUtilitiesClass();
            
            //gpu.DecodeFeatureLayer(result.GetOutput(0), out out_featureClass,out qf);
            IGPValue resultValue = result.GetOutput(0);
            //ITable table = (ITable)out_featureClass;
            //MessageBox.Show(table.RowCount(qf).ToString());

            //ICursor resultCursor = (ICursor)in_feature.search;

            MessageBox.Show(resultValue.GetAsText());
            //MessageBox.Show(resultCursor.Fields.FieldCount.ToString());
            ITnToolsTable toolTable = new TnTools();
            //MessageBox.Show(resultCursor.Fields.FieldCount.ToString());
            //toolTable.TnShowDataWithGivenCursor(resultCursor, dataGridView, "SO_THUA,TENCHU", "", 1);
            
            

            ESRI.ArcGIS.DataManagementTools.SelectLayerByAttribute selectAttTool = new ESRI.ArcGIS.DataManagementTools.SelectLayerByAttribute();
            selectAttTool.in_layer_or_view = select_featureLayer;
            selectAttTool.where_clause = "TENCHU='4'";
            selectAttTool.selection_type="NEW_SELECTION";
            gp.Execute(selectAttTool, null);
            
            //out_featureClass = wspTool.OpenFeatureClassFromFileMdb(_mdbTempFolder + "\\" + _mdbTempFileName, out_feature);
            //out_featureClass = wspTool.OpenFeatureClassFromSDE(workspace, out_feature);
            //return out_feature;
        }

        string ITnToolsSpatial.TnIntersectSelection(string in_featureClass, string select_featureClass, string environmentGP, string environmentTemp)
        {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 1: Make feature layers using the MakeFeatureLayer tool for the inputs to the SelectByLocation tool.
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Intialize the Geoprocessor 
            Geoprocessor GP = new Geoprocessor();

            // Intialize the MakeFeatureLayer tool
            MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();
            makefeaturelayer.in_features = @"C:\tayninh\temp\tempmdb.mdb\p2_duong_buff_50";
            makefeaturelayer.out_layer = "gt_buff_lyr";
            RunTool(GP, makefeaturelayer, null);
            //GP.SetEnvironmentValue("workspace","Database Connections/Connection to ht_laptop.sde");
            GP.ResetEnvironments();
            makefeaturelayer.in_features = "Database Connections/Connection to HT-LAPTOP.sde/P2_THUA";//@"C:\tayninh\temp\tempmdb.mdb\p2_thua";
            makefeaturelayer.out_layer = "p2_sde_thua_lyr";
            RunTool(GP, makefeaturelayer, null);
            GP.ResetEnvironments();
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 2: Execute SelectLayerByLocation using the feature layers to select all wells that intersect theb bedrock geololgy.
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Intialize the SelectLayerByLocation tool
            SelectLayerByLocation SelectByLocation = new SelectLayerByLocation();

            SelectByLocation.in_layer = "p2_sde_thua_lyr";
            SelectByLocation.select_features = "gt_buff_lyr";
            SelectByLocation.overlap_type = "INTERSECT";

            ILayerFile lf = new LayerFileClass();


            IFeatureClass fc;
            IQueryFilter qf;
            //IGeoProcessorResult result = (IGeoProcessorResult)GP.Execute(SelectByLocation, null);
            IGPUtilities gpu = new GPUtilitiesClass();
            //gpu.DecodeFeatureLayer(result.GetOutput(0), out fc, out qf);
            RunTool(GP, SelectByLocation, null);

            /////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 3: Execute SelectLayerByAttribute to select all wells that have a well yield > 150 L/min.
            /////////////////////////////////////////////////////////////////////////////////////////////////

            // Intialize the SelectLayerByAttribute tool
            SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();
            IRow r;
            ITableSelection t;


            //SelectByAttribute.in_layer_or_view = "p2_thua_lyr";
            //SelectByAttribute.selection_type = "NEW_SELECTION";
            //SelectByAttribute.where_clause = "";
            //RunTool(GP, SelectByAttribute, null);

            SaveToLayerFile saveLayer = new SaveToLayerFile();
            saveLayer.in_layer = "p2_sde_thua_lyr";
            saveLayer.out_layer = @"C:\tayninh\temp\p2_sde_thua_lyr_save2.lyr";

            RunTool(GP, saveLayer, null);
            ////////////////////////////////////////////////////////////////////////////////////////////////////////
            // STEP 4: Execute CopyFeatures tool to create a new feature class of wells with well yield > 150 L/min.
            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            // Intialize the CopyFeatures tool
            CopyFeatures CopyFeatures = new CopyFeatures();

            //CopyFeatures.in_features = fc;
            //CopyFeatures.out_feature_class = @"C:\tayninh\temp\tempmdb.mdb\p2_thua_lyr_d";

            // Set the output Coordinate System environment
            //GP.SetEnvironmentValue("outputCoordinateSystem",
            //@"C:\Program Files\ArcGIS\Coordinate Systems\Projected Coordinate Systems\UTM\Nad 1983\NAD 1983 UTM Zone 21N.prj");

            //RunTool(GP, CopyFeatures, null);
            IWorkspace w;
            
            
            
            return @"C:\tayninh\temp\p2_sde_thua_lyr_save2.lyr";
        }
        IFeatureLayer ITnToolsSpatial.TnIntersection(string in_featureClass, string select_featureClass, IWorkspaceEdit workspace)
        {
            try
            {
                //Geoprocessor GP = new Geoprocessor();
                IFeatureCursor featureCursor;
                IFeatureClass featureClass;
                IFeature feature;
                IFeatureClass thua;
                IGeometryCollection geometryCollection=new GeometryBagClass();
                ITnToolsWorkspace toolWorkspace=new TnTools();
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(workspace,select_featureClass);
                thua = toolWorkspace.OpenFeatureClassFromSDE(workspace,in_featureClass);
                featureCursor = featureClass.Search(null, true);
                object obj = Type.Missing;
                feature = featureCursor.NextFeature();
                while (feature != null)
                {
                    geometryCollection.AddGeometry(feature.Shape,ref obj,ref obj);
                    feature = featureCursor.NextFeature();
                }

                SpatialFilter spatialFilter = new SpatialFilter();
                spatialFilter.Geometry = geometryCollection.get_Geometry(1);
                spatialFilter.GeometryField = thua.ShapeFieldName;
                spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                
                IFeatureSelection featureSelection;
                IFeatureLayer thuaLayer = new FeatureLayerClass();
                
                thuaLayer.FeatureClass = thua;
                
                IQueryFilter qf = spatialFilter;
                //ISelectionSet selectionSet;
                
                IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)thuaLayer;
                //flDef.DefinitionExpression = "SO_TO ='3.0'";
                featureSelection = (IFeatureSelection)thuaLayer;
                featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                
                //selectionSet = thua.Select(spatialFilter, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, null);
                
                
                IFeatureLayer selectLayer = flDef.CreateSelectionLayer("newlayer", true, null, null);
                IFeatureClass selectClass = selectLayer.FeatureClass;
                IFeatureCursor fCursor = selectLayer.Search(null,false);
                IFeature ft = fCursor.NextFeature();
                int a = 0;
                while (ft != null)
                {
                    a = a + 1;
                    // ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU"));
                    //MessageBox.Show(ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU")).Editable.ToString());
                    ft.set_Value(ft.Fields.FindFieldByAliasName("GHI_CHU"),"inter");
                    //fCursor.UpdateFeature(ft);
                    ft.Store();
                    //MessageBox.Show(ft.get_Value(ft.Fields.FindFieldByAliasName("GHI_CHU")).ToString());
                    ft = fCursor.NextFeature();
                    
                }
                
                MessageBox.Show(a.ToString());
                
                ITable table = (ITable)selectClass;
                return selectLayer;
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); return null; }
            
        
        }
        IFeatureLayer ITnToolsSpatial.TnIntersectionThuaMatTien(string in_featureClass, string select_featureClass, IWorkspaceEdit workspace)
        {
            try
            {
                //Geoprocessor GP = new Geoprocessor();
                IFeatureCursor featureCursor;
                IFeatureClass featureClass;
                IFeature feature;
                IFeatureClass thua;
                IGeometryCollection geometryCollection = new GeometryBagClass();
                ITnToolsWorkspace toolWorkspace = new TnTools();
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(workspace, select_featureClass);
                thua = toolWorkspace.OpenFeatureClassFromSDE(workspace, in_featureClass);
                featureCursor = featureClass.Search(null, true);
                object obj = Type.Missing;
                feature = featureCursor.NextFeature();
                int a = 0;
                SpatialFilter spatialFilter = new SpatialFilter();
                IFeatureSelection featureSelection;
                IFeatureLayer thuaLayer = new FeatureLayerClass();
                thuaLayer.FeatureClass = thua;
                IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)thuaLayer;
                IFeatureLayer selectLayer = null;
                IFeatureClass selectClass = null;
                IFeatureCursor fCursor;
                IFeature ft;
                string strMaDuong;
                int intSomattien=0;
                double dblDongia=0;
                double dblGiadat = 0;
                double dblGiadat1 = 0;
                double dblGiadat2 = 0;
                double dblDientich1 = 0;
                double dblDientich2 = 0;
                string strKdat = "";
                string strGhichu = "";
                int i = 0;
                IArea area;
                while (feature != null)
                {
                    //intSomattien = intSomattien + 1;
                    geometryCollection.AddGeometry(feature.Shape, ref obj, ref obj);
                    //if (feature.get_Value(feature.Fields.FindField("giadat")).ToString()!="")
                    //{
                    dblDongia = Convert.ToDouble(feature.get_Value(feature.Fields.FindField("giadat")));
                    //}
                    //else
                    //{
                    //    dblDongia = 0;
                    //}
                    
                    spatialFilter.Geometry = feature.Shape;
                    spatialFilter.GeometryField = thua.ShapeFieldName;
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                    strMaDuong =feature.get_Value(feature.Fields.FindField("maduong")).ToString();

                    //ISelectionSet selectionSet;


                    //flDef.DefinitionExpression = "SO_TO ='3.0'";
                    featureSelection = (IFeatureSelection)thuaLayer;
                    featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

                    //selectionSet = thua.Select(spatialFilter, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, null);


                    selectLayer = flDef.CreateSelectionLayer("newlayer", true, null, null);
                    selectClass = selectLayer.FeatureClass;
                    fCursor = selectLayer.Search(null, false);
                    ft = fCursor.NextFeature();
                    a = 0;
                    while (ft != null)
                    {
                        a = a + 1;
                        // ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU"));
                        //MessageBox.Show(ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU")).Editable.ToString());
                        //ft.set_Value(ft.Fields.FindFieldByAliasName("GHI_CHU"), "inter");
                        //if (ft.get_Value(ft.Fields.FindFieldByAliasName("somattien")) != null)
                        //{
                            intSomattien =int.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("somattien")).ToString());
                        //}
                        
                        switch (intSomattien)
                        {
                            case 0:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 1);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                strGhichu += "Mặt tiền 1: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strMaDuong.Clone().ToString());
                                break;
                            case 1:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 2);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 2: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                }
                                break;
                            case 2:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 3);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 3: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu.ToString());
                                }
                                break;
                            case 3:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 4);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 4: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                }
                                break;
                            default:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 1);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                strGhichu += "--Mặt tiền 1: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                break;
                        }
                        
                        area =(IArea) ft.Shape;
                        ft.set_Value(ft.Fields.FindFieldByAliasName("dientich1"), area.Area);
                        ft.set_Value(ft.Fields.FindFieldByAliasName("kdat"), "30");
                        
                        //fCursor.UpdateFeature(ft);
                        ft.Store();
                        //MessageBox.Show(ft.get_Value(ft.Fields.FindFieldByAliasName("GHI_CHU")).ToString());
                        ft = fCursor.NextFeature();

                    }
                    i = i + 1;
                    feature = featureCursor.NextFeature();
                    
                }
                //////////////////////////////////////////////////////////////////
                //Tim thua mat tien tron thua
                //////////////////////////////////////////////////////////////////
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(workspace, "tn_duong_buff_50");
                //thua = toolWorkspace.OpenFeatureClassFromSDE(workspace, in_featureClass);
                featureCursor = featureClass.Search(null, true);

                //object obj = Type.Missing;
                feature = featureCursor.NextFeature();
                
                //flDef.DefinitionExpression = "kdat=30";
                while (feature != null)
                {
                    geometryCollection.AddGeometry(feature.Shape, ref obj, ref obj);

                    spatialFilter.Geometry = feature.Shape;
                    spatialFilter.GeometryField = thua.ShapeFieldName;
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin;

                    strMaDuong = feature.get_Value(feature.Fields.FindField("maduong")).ToString();
                    //flDef.DefinitionExpression += " and maduong='" + strMaDuong + "'";

                    featureSelection = (IFeatureSelection)thuaLayer;
                    //featureSelection.Clear();
                    featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                    //MessageBox.Show(featureSelection.SelectionSet.Count.ToString());
                    selectLayer = flDef.CreateSelectionLayer("layerMt", true, null, null);
                    selectClass = selectLayer.FeatureClass;
                    fCursor = selectLayer.Search(null, false);
                    ft = fCursor.NextFeature();
                    while (ft != null)
                    {
                        dblDongia=double.Parse(ft.get_Value(ft.Fields.FindField("dongia")).ToString());
                        ft.set_Value(ft.Fields.FindFieldByAliasName("dientich2"), 0);
                        dblDientich1 = double.Parse(ft.get_Value(ft.Fields.FindField("dientich1")).ToString());
                        dblGiadat1 = dblDientich1 * dblDongia;
                        dblGiadat2 = 0;
                        dblGiadat = dblGiadat1 + dblGiadat2;
                        if (dblGiadat > double.Parse(ft.get_Value(ft.Fields.FindField("giadat")).ToString()))
                        {
                            ft.set_Value(ft.Fields.FindFieldByAliasName("giadat"), dblGiadat);
                            ft.set_Value(ft.Fields.FindFieldByAliasName("giadat1"), dblGiadat1);
                            //ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                        }
                        //kdat = ft.get_Value(ft.Fields.FindField("kdat")).ToString();
                        ft.set_Value(ft.Fields.FindFieldByAliasName("kdat"), "3010");
                        ft.set_Value(ft.Fields.FindFieldByAliasName("locked"), 1);
                        ft.Store();
                        ft = fCursor.NextFeature();
                    }
                    //tìm thửa mặt tiền dài hơn 50m
                    //flDef.DefinitionExpression += " and locked='0'";
                    //featureSelection = (IFeatureSelection)thuaLayer;
                    //featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

                    feature = featureCursor.NextFeature();
                }

                MessageBox.Show(a.ToString());

                //ITable table = (ITable)selectClass;
                return selectLayer;
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); return null; }
        }

        #endregion //ITnToolsSpatial

        #region ITnToolsTable Members

        void ITnToolsTable.TnShowData(IWorkspaceEdit workspace,DataGridView dataGridView, string nameTable,string nameFields, string dieukien, int gioihan)
        {
            //string strNameTable="THUA";
            //ITnToolsTable toolTable = new TnTools();
            string strNameFields = nameFields;//"SO_THUA,TENCHU";
            string strDieukien = "";
            switch (gioihan)
            {
                case 0:
                    strDieukien = "TENCHU='4'";
                    break;
                default:
                    strDieukien = "";
                    break;
            }

            IFeatureClass featureClassThua = this._sdeFeatureWorkspace.OpenFeatureClass(nameTable);
            //ITable tblThua = (ITable)featureClassThua;
            ICursor cursor = ((ITnToolsTable)this).TnQueryAttribute(this.SdeWorkspace, nameTable, strNameFields, strDieukien);
            //IFeature feature = null;
            IRow row = null;
            String[] strRow = new string[cursor.Fields.FieldCount];
            //gan cac cot cua bang truy van vao datagridview thua
            dataGridView.ColumnCount = cursor.Fields.FieldCount;
            for (int i = 0; i < cursor.Fields.FieldCount; i++)
            {
                dataGridView.Columns[i].Name = cursor.Fields.get_Field(i).Name;
            }

            try
            {
                dataGridView.Rows.Clear();
                while ((row = cursor.NextRow()) != null)
                {
                    for (int i = 0; i < cursor.Fields.FieldCount; i++)
                    {
                        strRow[i] = row.get_Value(i).ToString();
                    }
                    dataGridView.Rows.Add(strRow);
                    strRow = new String[cursor.Fields.FieldCount];
                    //row = cursor.NextRow();
                    //MessageBox.Show("doi tuong: " + row.get_Value(1));
                }
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); }
            Marshal.ReleaseComObject(cursor);
        }
        void ITnToolsTable.TnShowData(IWorkspaceEdit workspace, DataGridView dataGridView, IFeatureClass table,string nameFields, string dieukien, int gioihan)
        {
            //string strNameTable="THUA";
            //ITnToolsTable toolTable = new TnTools();
            string strNameFields = nameFields;//"SO_THUA,TENCHU";
            string strDieukien = "";
            switch (gioihan)
            {
                case 0:
                    strDieukien = "";//"TENCHU='4'";
                    break;
                default:
                    strDieukien = "";
                    break;
            }

            IFeatureClass featureClass = table;
            //ITable tblThua = (ITable)featureClassThua;
            ICursor cursor = ((ITnToolsTable)this).TnQueryAttribute(workspace, table, strNameFields, strDieukien);
            //IFeature feature = null;
            IRow row = null;
            String[] strRow = new string[cursor.Fields.FieldCount];
            
            //gan cac cot cua bang truy van vao datagridview thua
            dataGridView.ColumnCount = cursor.Fields.FieldCount;
            for (int i = 0; i < cursor.Fields.FieldCount; i++)
            {
                dataGridView.Columns[i].Name = cursor.Fields.get_Field(i).Name;
            }

            try
            {
                dataGridView.Rows.Clear();
                while ((row = cursor.NextRow()) != null)
                {
                    for (int i = 0; i < cursor.Fields.FieldCount; i++)
                    {
                        strRow[i] = row.get_Value(i).ToString();
                    }
                    dataGridView.Rows.Add(strRow);
                    strRow = new String[cursor.Fields.FieldCount];
                    //row = cursor.NextRow();
                    //MessageBox.Show("doi tuong: " + row.get_Value(1));
                }
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); }
            Marshal.ReleaseComObject(cursor);
        }
        void ITnToolsTable.TnShowDataWithGivenCursor(ICursor _cursor, DataGridView dataGridView, string nameFields, string dieukien, int gioihan)
        {
            string strNameFields = nameFields;//"SO_THUA,TENCHU";
            string strDieukien = "";
            switch (gioihan)
            {
                case 0:
                    strDieukien = "";//"TENCHU='4'";
                    break;
                default:
                    strDieukien = "";
                    break;
            }



            ICursor cursor = _cursor;//this.TnQueryAttribute(this.SdeWorkspace, table, strNameFields, strDieukien);
            //IFeature feature = null;
            IRow row = null;
            String[] strRow = new string[cursor.Fields.FieldCount];
            
            //gan cac cot cua bang truy van vao datagridview thua
            dataGridView.ColumnCount = cursor.Fields.FieldCount;
            //MessageBox.Show(_cursor.Fields.FieldCount.ToString());
            for (int i = 0; i < _cursor.Fields.FieldCount; i++)
            {
                dataGridView.Columns[i].Name = _cursor.Fields.get_Field(i).Name;
            }

            try
            {
                dataGridView.Rows.Clear();
                while ((row = _cursor.NextRow()) != null)
                {
                    for (int i = 0; i < _cursor.Fields.FieldCount; i++)
                    {
                        strRow[i] = row.get_Value(i).ToString();
                    }
                    dataGridView.Rows.Add(strRow);
                    strRow = new String[_cursor.Fields.FieldCount];
                    //row = cursor.NextRow();
                    //MessageBox.Show("doi tuong: " + row.get_Value(1));
                }
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); }
            Marshal.ReleaseComObject(_cursor);
        }
        ICursor ITnToolsTable.TnQueryAttribute(IWorkspaceEdit workspace, string table, string fields, string dieukien)
        {
            IQueryFilter queryFilter = new QueryFilterClass();
            IQueryDef queryDef = this._sdeFeatureWorkspace.CreateQueryDef();

            //cac truong tra ve
            //queryFilter.SubFields="SO_THUA, TENCHU";
            queryDef.Tables = table;
            queryDef.SubFields = "SO_THUA,TENCHU";
            queryDef.WhereClause = dieukien;
            ICursor cursor = queryDef.Evaluate();

            //queryFilter.WhereClause = dieukien;

            //IQueryFilterDefinition queryFilterDef = (IQueryFilterDefinition)queryFilter;
            //queryFilterDef.PostfixClause = "ORDER BY SO_TO";

            //ICursor cursor = table.Search(queryFilter, false);
            return cursor;
        }
        ICursor ITnToolsTable.TnQueryAttribute(IWorkspaceEdit workspace, IFeatureClass table, string fields, string dieukien)
        {
            IQueryFilter queryFilter = new QueryFilterClass();
            IFeatureWorkspace fws=(IFeatureWorkspace)workspace;
            IQueryDef queryDef = fws.CreateQueryDef();

            //cac truong tra ve
            //queryFilter.SubFields="SO_THUA, TENCHU";
            queryDef.Tables = table.AliasName;
            queryDef.SubFields = fields;
            queryDef.WhereClause = dieukien;
            ICursor cursor = queryDef.Evaluate();

            //queryFilter.WhereClause = dieukien;

            //IQueryFilterDefinition queryFilterDef = (IQueryFilterDefinition)queryFilter;
            //queryFilterDef.PostfixClause = "ORDER BY SO_TO";

            //ICursor cursor = table.Search(queryFilter, false);
            return cursor;
        }

        void ITnToolsTable.TnFormatTable(IWorkspaceEdit workspace, string thua, string duong, string hem)
        {
            ITnToolsWorkspace workspaceTool = new TnTools();
            IFeatureClass thuafc = workspaceTool.OpenFeatureClassFromSDE(workspace, thua);
            IFeatureClass duongfc = workspaceTool.OpenFeatureClassFromSDE(workspace, duong);
            IFeatureClass hemfc = workspaceTool.OpenFeatureClassFromSDE(workspace, hem);
            IFeatureCursor fcursor = thuafc.Search(null, false);
            IFeature ft = fcursor.NextFeature();
            while (ft != null)
            {
                ft.set_Value(ft.Fields.FindField("somattien"), 0);
                ft.set_Value(ft.Fields.FindField("dongia"), 0);
                ft.set_Value(ft.Fields.FindField("dientich1"), 0);
                ft.set_Value(ft.Fields.FindField("dientich2"), 0);
                ft.set_Value(ft.Fields.FindField("locked"), 0);
                ft.set_Value(ft.Fields.FindField("giadat"), 0);
                ft.set_Value(ft.Fields.FindField("giadat1"), 0);
                ft.set_Value(ft.Fields.FindField("giadat2"), 0);
                ft.set_Value(ft.Fields.FindField("kdat"), "0");
                ft.set_Value(ft.Fields.FindField("ghichu"), "");
                ft.Store();
                ft = fcursor.NextFeature();
            }
        }
        void ITnToolsTable.TnFormatTable(IWorkspaceEdit workspace, string table)
        {
            //ITnToolsWorkspace workspaceTool = new TnTools();
            IFeatureClass fc = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, table);
            
            IFeatureCursor fcursor = fc.Search(null, false);
            IFeature ft = fcursor.NextFeature();
            if (table == "tn_thua")
            {
                while (ft != null)
                {
                    ft.set_Value(ft.Fields.FindField("somattien"), 0);
                    ft.set_Value(ft.Fields.FindField("dongia"), 0);
                    ft.set_Value(ft.Fields.FindField("dientich1"), 0);
                    ft.set_Value(ft.Fields.FindField("dientich2"), 0);
                    ft.set_Value(ft.Fields.FindField("locked"), 0);
                    ft.set_Value(ft.Fields.FindField("giadat"), 0);
                    ft.set_Value(ft.Fields.FindField("giadat1"), 0);
                    ft.set_Value(ft.Fields.FindField("giadat2"), 0);
                    ft.set_Value(ft.Fields.FindField("kdat"), "0");
                    ft.set_Value(ft.Fields.FindField("ghichu"), "");
                    ft.Store();
                    ft = fcursor.NextFeature();
                }
            }
            else if (table == "tn_duong_buff_05" || table == "tn_duong_buff_50" || table == "tn_duong_buff_100" || table == "tn_duong")
            {
                //while (ft != null)
                //{
                //    ft.set_Value(ft.Fields.FindField("somattien"), 0);
                //    ft.Store();
                //    ft = fcursor.NextFeature();
                //}
            }
        }
        void ITnToolsTable.TnFormatColumn(IWorkspaceEdit workspace, string table, string column,object value)
        {
            IFeatureClass fc = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, table);

            IFeatureCursor fcursor = fc.Search(null, false);
            IFeature ft = fcursor.NextFeature();
            while (ft != null)
            {
                ft.set_Value(ft.Fields.FindField(column), value);
                ft.Store();
                ft = fcursor.NextFeature();
            }
        }

        void ITnToolsTable.TnFormatColumn(IWorkspaceEdit workspace, string table, string column, object value,string dieukien)
        {
            IFeatureClass fc = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, table);
            IQueryFilter qf = new QueryFilterClass();
            qf.SubFields = "*";
            qf.WhereClause = dieukien;
            IFeatureCursor fcursor = fc.Search(qf, false);
            IFeature ft = fcursor.NextFeature();
            while (ft != null)
            {
                ft.set_Value(ft.Fields.FindField(column), value);
                ft.Store();
                ft = fcursor.NextFeature();
            }
        }
        
        #endregion //ITnToolsTable

        //#region ITnToolsTable Members


        //public void TnShowDataWithGivenCursor(ICursor cursor, DataGridView dataGridView, string nameFields, string dieukien, int gioihan)
        //{
        //    throw new NotImplementedException();
        //}

        //#endregion
        private static void RunTool(Geoprocessor geoprocessor, IGPProcess process, ITrackCancel TC)
        {

            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;

            // Execute the tool            
            try
            {
                geoprocessor.Execute(process, TC);
                ReturnMessages(geoprocessor);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                ReturnMessages(geoprocessor);
            }
        }
        private static void RunTool(Geoprocessor geoprocessor, IGPProcess process,IVariantArray param, ITrackCancel TC)
        {

            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;

            // Execute the tool            
            try
            {
                geoprocessor.Execute("Clip_analysis" ,param,TC);
                ReturnMessages(geoprocessor);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                ReturnMessages(geoprocessor);
            }
        }
        private static void ReturnMessages(Geoprocessor gp)
        {
            if (gp.MessageCount > 0)
            {
                for (int Count = 0; Count <= gp.MessageCount - 1; Count++)
                {
                    Console.WriteLine(gp.GetMessage(Count));
                }
            }

        }


        #region ITnToolsCalculator Members

        IFeatureLayer ITnToolsCalculator.TnTinhThuaMattien(string in_featureClass, string select_featureClass, IWorkspaceEdit workspace)
        {
            try
            {
                //Geoprocessor GP = new Geoprocessor();
                IFeatureCursor featureCursor;
                IFeatureClass featureClass;
                IFeature feature;
                IFeatureClass thua;
                IGeometryCollection geometryCollection = new GeometryBagClass();
                ITnToolsWorkspace toolWorkspace = new TnTools();
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(workspace, select_featureClass);
                thua = toolWorkspace.OpenFeatureClassFromSDE(workspace, in_featureClass);
                featureCursor = featureClass.Search(null, true);
                object obj = Type.Missing;
                feature = featureCursor.NextFeature();
                int a = 0;
                SpatialFilter spatialFilter = new SpatialFilter();
                IFeatureSelection featureSelection;
                IFeatureLayer thuaLayer = new FeatureLayerClass();
                thuaLayer.FeatureClass = thua;
                IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)thuaLayer;
                IFeatureLayer selectLayer = null;
                IFeatureClass selectClass = null;
                IFeatureCursor fCursor;
                IFeature ft;
                string strMaDuong;
                int intSomattien = 0;
                double dblDongia = 0;
                double dblGiadat = 0;
                double dblGiadat1 = 0;
                double dblGiadat2 = 0;
                double dblDientich1 = 0;
                double dblDientich2 = 0;
                string strKdat = "";
                string strGhichu = "";
                int i = 0;
                IArea area;
                while (feature != null)
                {
                    //intSomattien = intSomattien + 1;
                    geometryCollection.AddGeometry(feature.Shape, ref obj, ref obj);
                    //if (feature.get_Value(feature.Fields.FindField("giadat")).ToString()!="")
                    //{
                    dblDongia = Convert.ToDouble(feature.get_Value(feature.Fields.FindField("giadat")));
                    //}
                    //else
                    //{
                    //    dblDongia = 0;
                    //}

                    spatialFilter.Geometry = feature.Shape;
                    spatialFilter.GeometryField = thua.ShapeFieldName;
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                    strMaDuong = feature.get_Value(feature.Fields.FindField("maduong")).ToString();

                    //ISelectionSet selectionSet;


                    //flDef.DefinitionExpression = "SO_TO ='3.0'";
                    featureSelection = (IFeatureSelection)thuaLayer;
                    featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

                    //selectionSet = thua.Select(spatialFilter, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, null);


                    selectLayer = flDef.CreateSelectionLayer("newlayer", true, null, null);
                    selectClass = selectLayer.FeatureClass;
                    fCursor = selectLayer.Search(null, false);
                    ft = fCursor.NextFeature();
                    a = 0;
                    while (ft != null)
                    {
                        a = a + 1;
                        // ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU"));
                        //MessageBox.Show(ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU")).Editable.ToString());
                        //ft.set_Value(ft.Fields.FindFieldByAliasName("GHI_CHU"), "inter");
                        //if (ft.get_Value(ft.Fields.FindFieldByAliasName("somattien")) != null)
                        //{
                        intSomattien = int.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("somattien")).ToString());
                        //}

                        switch (intSomattien)
                        {
                            case 0:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 1);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                strGhichu += "Mặt tiền 1: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strMaDuong.Clone().ToString());
                                break;
                            case 1:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 2);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 2: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                }
                                break;
                            case 2:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 3);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 3: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu.ToString());
                                }
                                break;
                            case 3:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 4);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 4: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                }
                                break;
                            default:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 1);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                strGhichu += "--Mặt tiền 1: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                break;
                        }

                        area = (IArea)ft.Shape;
                        ft.set_Value(ft.Fields.FindFieldByAliasName("dientich1"), area.Area);
                        ft.set_Value(ft.Fields.FindFieldByAliasName("kdat"), "30");

                        //fCursor.UpdateFeature(ft);
                        ft.Store();
                        //MessageBox.Show(ft.get_Value(ft.Fields.FindFieldByAliasName("GHI_CHU")).ToString());
                        ft = fCursor.NextFeature();

                    }
                    i = i + 1;
                    feature = featureCursor.NextFeature();

                }
                //////////////////////////////////////////////////////////////////
                //Tim thua mat tien tron thua
                //////////////////////////////////////////////////////////////////
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(workspace, "tn_duong_buff_50");
                //thua = toolWorkspace.OpenFeatureClassFromSDE(workspace, in_featureClass);
                featureCursor = featureClass.Search(null, true);

                //object obj = Type.Missing;
                feature = featureCursor.NextFeature();

                //flDef.DefinitionExpression = "kdat=30";
                while (feature != null)
                {
                    geometryCollection.AddGeometry(feature.Shape, ref obj, ref obj);

                    spatialFilter.Geometry = feature.Shape;
                    spatialFilter.GeometryField = thua.ShapeFieldName;
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin;

                    strMaDuong = feature.get_Value(feature.Fields.FindField("maduong")).ToString();
                    //flDef.DefinitionExpression += " and maduong='" + strMaDuong + "'";

                    featureSelection = (IFeatureSelection)thuaLayer;
                    //featureSelection.Clear();
                    featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                    //MessageBox.Show(featureSelection.SelectionSet.Count.ToString());
                    selectLayer = flDef.CreateSelectionLayer("layerMt", true, null, null);
                    selectClass = selectLayer.FeatureClass;
                    fCursor = selectLayer.Search(null, false);
                    ft = fCursor.NextFeature();
                    while (ft != null)
                    {
                        dblDongia = double.Parse(ft.get_Value(ft.Fields.FindField("dongia")).ToString());
                        ft.set_Value(ft.Fields.FindFieldByAliasName("dientich2"), 0);
                        dblDientich1 = double.Parse(ft.get_Value(ft.Fields.FindField("dientich1")).ToString());
                        dblGiadat1 = dblDientich1 * dblDongia;
                        dblGiadat2 = 0;
                        dblGiadat = dblGiadat1 + dblGiadat2;
                        if (dblGiadat > double.Parse(ft.get_Value(ft.Fields.FindField("giadat")).ToString()))
                        {
                            ft.set_Value(ft.Fields.FindFieldByAliasName("giadat"), dblGiadat);
                            ft.set_Value(ft.Fields.FindFieldByAliasName("giadat1"), dblGiadat1);
                            //ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                        }
                        //kdat = ft.get_Value(ft.Fields.FindField("kdat")).ToString();
                        ft.set_Value(ft.Fields.FindFieldByAliasName("kdat"), "3010");
                        ft.set_Value(ft.Fields.FindFieldByAliasName("locked"), 1);
                        ft.Store();
                        ft = fCursor.NextFeature();
                    }
                    //tìm thửa mặt tiền dài hơn 50m
                    //flDef.DefinitionExpression += " and locked='0'";
                    //featureSelection = (IFeatureSelection)thuaLayer;
                    //featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

                    feature = featureCursor.NextFeature();
                }

                //MessageBox.Show(a.ToString());

                //ITable table = (ITable)selectClass;
                return selectLayer;
                
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); return null; }
        }

        IFeatureLayer ITnToolsCalculator.TnTinhThuaMattien2(string in_featureClass, string select_featureClass, IWorkspaceEdit workspace)
        {
            
            //////////////////////////////////////////////////////////////////
                //Tim thua mat tien tron thua
                //////////////////////////////////////////////////////////////////
            try
            {
                IFeatureCursor featureCursor;
                IFeatureClass featureClass;
                IFeature feature;
                IFeatureClass thua;
                IGeometryCollection geometryCollection = new GeometryBagClass();
                ITnToolsWorkspace toolWorkspace = new TnTools();
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(workspace, select_featureClass);
                thua = toolWorkspace.OpenFeatureClassFromSDE(workspace, in_featureClass);
                featureCursor = featureClass.Search(null, true);
                object obj = Type.Missing;
                feature = featureCursor.NextFeature();
                int a = 0;
                SpatialFilter spatialFilter = new SpatialFilter();
                IFeatureSelection featureSelection;
                IFeatureLayer thuaLayer = new FeatureLayerClass();
                thuaLayer.FeatureClass = thua;
                IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)thuaLayer;
                IFeatureLayer selectLayer = null;
                IFeatureClass selectClass = null;
                IFeatureCursor fCursor;
                IFeature ft;
                string strMaDuong;
                int intSomattien = 0;
                double dblDongia = 0;
                double dblGiadat = 0;
                double dblGiadat1 = 0;
                double dblGiadat2 = 0;
                double dblDientich1 = 0;
                double dblDientich2 = 0;
                string strKdat = "";
                string strGhichu = "";
                int i = 0;
                IArea area;
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(workspace, "tn_duong_buff_50");
                //thua = toolWorkspace.OpenFeatureClassFromSDE(workspace, in_featureClass);
                featureCursor = featureClass.Search(null, true);

                //object obj = Type.Missing;
                feature = featureCursor.NextFeature();

                //flDef.DefinitionExpression = "kdat=30";
                while (feature != null)
                {
                    geometryCollection.AddGeometry(feature.Shape, ref obj, ref obj);

                    spatialFilter.Geometry = feature.Shape;
                    spatialFilter.GeometryField = thua.ShapeFieldName;
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin;

                    strMaDuong = feature.get_Value(feature.Fields.FindField("maduong")).ToString();
                    //flDef.DefinitionExpression += " and maduong='" + strMaDuong + "'";

                    featureSelection = (IFeatureSelection)thuaLayer;
                    //featureSelection.Clear();
                    featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                    //MessageBox.Show(featureSelection.SelectionSet.Count.ToString());
                    selectLayer = flDef.CreateSelectionLayer("layerMt", true, null, null);
                    selectClass = selectLayer.FeatureClass;
                    fCursor = selectLayer.Search(null, false);
                    ft = fCursor.NextFeature();
                    while (ft != null)
                    {
                        dblDongia = double.Parse(ft.get_Value(ft.Fields.FindField("dongia")).ToString());
                        ft.set_Value(ft.Fields.FindFieldByAliasName("dientich2"), 0);
                        dblDientich1 = double.Parse(ft.get_Value(ft.Fields.FindField("dientich1")).ToString());
                        dblGiadat1 = dblDientich1 * dblDongia;
                        dblGiadat2 = 0;
                        dblGiadat = dblGiadat1 + dblGiadat2;
                        if (dblGiadat > double.Parse(ft.get_Value(ft.Fields.FindField("giadat")).ToString()))
                        {
                            ft.set_Value(ft.Fields.FindFieldByAliasName("giadat"), dblGiadat);
                            ft.set_Value(ft.Fields.FindFieldByAliasName("giadat1"), dblGiadat1);
                            //ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                        }
                        //kdat = ft.get_Value(ft.Fields.FindField("kdat")).ToString();
                        ft.set_Value(ft.Fields.FindFieldByAliasName("kdat"), "3010");
                        ft.set_Value(ft.Fields.FindFieldByAliasName("locked"), 1);
                        ft.Store();
                        ft = fCursor.NextFeature();
                    }
                    //tìm thửa mặt tiền dài hơn 50m
                    flDef.DefinitionExpression += " and locked='0'";
                    featureSelection = (IFeatureSelection)thuaLayer;
                    featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

                    feature = featureCursor.NextFeature();
                }

                MessageBox.Show(a.ToString());

                //ITable table = (ITable)selectClass;
                return selectLayer;
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); return null; }
        }

        IFeatureLayer ITnToolsCalculator.TnTinhThuaHem(string in_featureClass, string select_featureClass, IWorkspaceEdit workspace)
        {
            try
            {
                //Geoprocessor GP = new Geoprocessor();
                IFeatureCursor featureCursor;
                IFeatureClass featureClass;
                IFeature feature;
                IFeatureClass thua;
                IGeometryCollection geometryCollection = new GeometryBagClass();
                ITnToolsWorkspace toolWorkspace = new TnTools();
                featureClass = toolWorkspace.OpenFeatureClassFromSDE(workspace, select_featureClass);
                thua = toolWorkspace.OpenFeatureClassFromSDE(workspace, in_featureClass);
                featureCursor = featureClass.Search(null, true);
                object obj = Type.Missing;
                feature = featureCursor.NextFeature();
                int a = 0;
                SpatialFilter spatialFilter = new SpatialFilter();
                IFeatureSelection featureSelection;
                IFeatureLayer thuaLayer = new FeatureLayerClass();
                thuaLayer.FeatureClass = thua;
                IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)thuaLayer;
                IFeatureLayer selectLayer = null;
                IFeatureClass selectClass = null;
                IFeatureCursor fCursor;
                IFeature ft;
                string strMaDuong;
                int intSomattien = 0;
                double dblDongia = 0;
                double dblGiadat = 0;
                double dblGiadat1 = 0;
                double dblGiadat2 = 0;
                double dblDientich1 = 0;
                double dblDientich2 = 0;
                string strKdat = "";
                string strGhichu = "";
                int i = 0;
                IArea area;
                while (feature != null)
                {
                    //intSomattien = intSomattien + 1;
                    geometryCollection.AddGeometry(feature.Shape, ref obj, ref obj);
                    //if (feature.get_Value(feature.Fields.FindField("giadat")).ToString()!="")
                    //{
                    dblDongia = Convert.ToDouble(feature.get_Value(feature.Fields.FindField("giadat")));
                    //}
                    //else
                    //{
                    //    dblDongia = 0;
                    //}

                    spatialFilter.Geometry = feature.Shape;
                    spatialFilter.GeometryField = thua.ShapeFieldName;
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                    strMaDuong = feature.get_Value(feature.Fields.FindField("maduong")).ToString();

                    //ISelectionSet selectionSet;


                    //flDef.DefinitionExpression = "SO_TO ='3.0'";
                    featureSelection = (IFeatureSelection)thuaLayer;
                    featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

                    //selectionSet = thua.Select(spatialFilter, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, null);


                    selectLayer = flDef.CreateSelectionLayer("newlayer", true, null, null);
                    selectClass = selectLayer.FeatureClass;
                    fCursor = selectLayer.Search(null, false);
                    ft = fCursor.NextFeature();
                    a = 0;
                    while (ft != null)
                    {
                        a = a + 1;
                        // ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU"));
                        //MessageBox.Show(ft.Fields.get_Field(ft.Fields.FindFieldByAliasName("GHI_CHU")).Editable.ToString());
                        //ft.set_Value(ft.Fields.FindFieldByAliasName("GHI_CHU"), "inter");
                        //if (ft.get_Value(ft.Fields.FindFieldByAliasName("somattien")) != null)
                        //{
                        intSomattien = int.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("somattien")).ToString());
                        //}

                        switch (intSomattien)
                        {
                            case 0:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 1);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                strGhichu += "Mặt tiền 1: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strMaDuong.Clone().ToString());
                                break;
                            case 1:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 2);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 2: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                }
                                break;
                            case 2:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 3);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 3: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu.ToString());
                                }
                                break;
                            case 3:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 4);
                                if (dblDongia > double.Parse(ft.get_Value(ft.Fields.FindFieldByAliasName("dongia")).ToString()))
                                {
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                    ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                    strGhichu += "--Mặt tiền 4: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                    //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                }
                                break;
                            default:
                                ft.set_Value(ft.Fields.FindFieldByAliasName("somattien"), 1);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("dongia"), dblDongia);
                                ft.set_Value(ft.Fields.FindFieldByAliasName("maduong"), strMaDuong);
                                strGhichu += "--Mặt tiền 1: Đường " + strMaDuong.ToString() + " ,đơn giá: " + dblDongia.ToString();
                                //ft.set_Value(ft.Fields.FindFieldByAliasName("ghichu"), strGhichu);
                                break;
                        }

                        area = (IArea)ft.Shape;
                        ft.set_Value(ft.Fields.FindFieldByAliasName("dientich1"), area.Area);
                        ft.set_Value(ft.Fields.FindFieldByAliasName("kdat"), "30");

                        //fCursor.UpdateFeature(ft);
                        ft.Store();
                        //MessageBox.Show(ft.get_Value(ft.Fields.FindFieldByAliasName("GHI_CHU")).ToString());
                        ft = fCursor.NextFeature();

                    }
                    i = i + 1;
                    feature = featureCursor.NextFeature();

                }

                MessageBox.Show(a.ToString());

                //ITable table = (ITable)selectClass;
                return selectLayer;
            }
            catch (Exception err) { MessageBox.Show(err.ToString()); return null; }
        }



        bool ITnToolsCalculator.TnIsLocked(IFeatureClass land, string strfield)
        {
            throw new NotImplementedException();
        }
        

        #endregion ITnToolsCalculator


        #region ITnToolsTable Members

        bool ITnToolsTable.TnCreateTable(string table_name, string[,] user_info, List<string[]> columns_with_type)
        {
            string strConnection="";
            string sql = "IF NOT EXISTS(SELECT * FROM sde.sde.SDE_layers WHERE table_name='"+table_name+"')";
            sql += " BEGIN CREATE TABLE " + table_name + "(";
            int col = 0;
            foreach (string[] column in columns_with_type)
            {
                if (col == columns_with_type.Count - 1)
                {
                    sql += column[0] + " " + column[1] + ");END";
                }
                else
                {
                    sql += column[0] + " " + column[1] + ",";
                }
                col++;
            }

            for (int i=0;i<user_info.Length/2;i++)
            {
                strConnection+=user_info[i,0]+"="+user_info[i,1];
                strConnection+=";";
            }
            SqlConnection conn = new SqlConnection(strConnection);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                
                conn.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch(Exception e)
            {
                //MessageBox.Show(e.ToString());
                //MessageBox.Show(sql);
                return false;
            }
            finally
            {
                conn.Close();
            }   
        }

        void ITnToolsTable.TnShowDataUseSQL(string server, string database, string user, string pass, string table, string dieukien, int gioihan, DataGridView dataGridView)
        {
            string connectString = "server=" + server + ";database=" + database + ";uid=" + user + ";pwd=" + pass;
            SqlConnection conn = new SqlConnection(connectString);
            string sql = "select * from " + table;

            if (dieukien != "")
            {
                sql += " where " + dieukien;
            }

            SqlCommand cmd = new SqlCommand(sql, conn);
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            String[] strRow = new string[reader.FieldCount];
            //MessageBox.Show(reader.FieldCount.ToString());
            dataGridView.ColumnCount = reader.FieldCount;
            for (int i = 0; i < reader.FieldCount; i++)
            {
                dataGridView.Columns[i].Name = reader.GetName(i);
            }
            dataGridView.Rows.Clear();
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    strRow[i] += reader.GetValue(i).ToString();
                }
                dataGridView.Rows.Add(strRow);
                strRow = new string[reader.FieldCount];
            }
        }

        #endregion

        #region ITnToolsTable Members

        SqlConnection ITnToolsTable.TnOpenConnection(string[,] user_info)
        {
            string strConnection = "";
            SqlConnection conn=new SqlConnection();
            try
            {
                for (int i = 0; i < user_info.Length / 2; i++)
                {
                    strConnection += user_info[i, 0] + "=" + user_info[i, 1];
                    strConnection += ";";
                }
                conn = new SqlConnection(strConnection);
                conn.Open();
                return conn;
            }
            catch
            {
                MessageBox.Show("loi ket noi SQL:"+conn.ToString());
                return null;
            }
            
        }

        List<string[]> ITnToolsTable.TnShowDataUseSQL(string server, string database, string user, string pass, string table, string dieukien, int gioihan)
        {
            string connectString = "server=" + server + ";database=" + database + ";uid=" + user + ";pwd=" + pass;
            SqlConnection conn = new SqlConnection(connectString);
            string sql = "select * from " + table;
            if (dieukien != "")
            {
                sql += " where " + dieukien;
            }
            SqlCommand cmd = new SqlCommand(sql, conn);
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            List<string[]> listVal=new List<string[]>();
            String[] strRow = new string[reader.FieldCount];
            //MessageBox.Show(reader.FieldCount.ToString());
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    strRow[i] += reader.GetValue(i).ToString();
                }
                listVal.Add(strRow);
                strRow = new string[reader.FieldCount];
            }
            return listVal;
        }

        List<string[]> ITnToolsTable.TnShowDataUseSQL(string[,] user_info, string table, string dieukien, int gioihan)
        {
            List<string[]> listVal = new List<string[]>();
            string strConnection = "";
            string sql = "select * from " + table;
            for (int i = 0; i < user_info.Length / 2; i++)
            {
                strConnection += user_info[i, 0] + "=" + user_info[i, 1];
                strConnection += ";";
            }
            SqlConnection conn = new SqlConnection(strConnection);
            if (dieukien != "")
            {
                sql += " where " + dieukien;
            }
            
            SqlCommand cmd = new SqlCommand(sql, conn);
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            String[] strRow = new string[reader.FieldCount];
            //MessageBox.Show(reader.FieldCount.ToString());
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    strRow[i] += reader.GetValue(i).ToString();
                }
                listVal.Add(strRow);
                strRow = new string[reader.FieldCount];
            }
            return listVal;
        }

        List<string[]> ITnToolsTable.TnShowDataUseSQL(SqlConnection sql_connection, string table, string dieukien, int gioihan)
        {
            //MessageBox.Show(sql_connection.ToString());
            List<string[]> listVal = new List<string[]>();
            //string strConnection = "";
            string sql = "select distinct * from " + table;
            //for (int i = 0; i < user_info.Length / 2; i++)
            //{
            //    strConnection += user_info[i, 0] + "=" + user_info[i, 1];
            //    strConnection += ";";
            //}
            //SqlConnection conn = new SqlConnection(strConnection);
            if (dieukien != "")
            {
                sql += " where " + dieukien;
            }

            SqlCommand cmd = new SqlCommand(sql, sql_connection);
            
            //conn.Open();
            SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SingleResult);
            String[] strRow = new string[reader.FieldCount];
            String[] strTemp = new string[reader.FieldCount];
            //MessageBox.Show(sql);
            
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    strRow[i] += reader.GetValue(i).ToString();
                }
                if(!strTemp.Equals(strRow))
                {
                    strTemp = strRow;
                    listVal.Add(strRow);
                }
                
                
                strRow = new string[reader.FieldCount];
            }
            reader.Close();
            return listVal;
        }

        List<string[]> ITnToolsTable.TnShowDataUseSQL(SqlConnection sql_connection, string table, out string[] field_name, string dieukien, int gioihan)
        {
            List<string[]> listVal = new List<string[]>();
            
            //string strConnection = "";
            string sql = "select * from " + table;//select distinct * from
            //for (int i = 0; i < user_info.Length / 2; i++)
            //{
            //    strConnection += user_info[i, 0] + "=" + user_info[i, 1];
            //    strConnection += ";";
            //}
            //SqlConnection conn = new SqlConnection(strConnection);
            if (dieukien != "")
            {
                sql += " where " + dieukien;
            }

            SqlCommand cmd = new SqlCommand(sql, sql_connection);

            //conn.Open();
            SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SingleResult);
            String[] strRow = new string[reader.FieldCount];
            String[] strTemp = new string[reader.FieldCount];
            field_name= new string[reader.FieldCount];
            //MessageBox.Show(sql);
            for (int i = 0; i < reader.FieldCount; i++)
            {
                field_name[i] = reader.GetName(i);
            }
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    strRow[i] += reader.GetValue(i).ToString();
                }
                if (!strTemp.Equals(strRow))
                {
                    strTemp = strRow;
                    listVal.Add(strRow);
                }


                strRow = new string[reader.FieldCount];
            }
            reader.Close();
            return listVal;
        }

        bool ITnToolsTable.TnInsertValue(SqlConnection sql_connection,string table_name, string[] fields, List<string[]> values)
        {
            string sql = "";
            int numValues=1;
            try
            {
                sql = "INSERT INTO " + table_name + "(";
                for (int i = 0; i < fields.Length; i++)
                {
                    sql += fields[i];
                    if (i != fields.Length - 1)
                    {
                        sql += ",";
                    }
                }
                sql += ") Values";
                foreach (string[] value in values)
                {
                    sql += "(";
                    for (int i = 0; i < value.Length; i++)
                    {
                        sql += value[i];
                        if (i != value.Length - 1)
                        {
                            sql += ",";
                        }
                    }
                    sql += ")";
                    if (numValues != values.Count)
                    {
                        sql += ",";
                    }
                    else
                    {
                        sql += ";";
                    }
                    numValues++;
                }

                SqlCommand cmd = new SqlCommand(sql, sql_connection);
                cmd.ExecuteNonQuery();
                return true;
            }
            catch(Exception e)
            {
                //MessageBox.Show(e.ToString());
                //MessageBox.Show(sql);
                return false;
            }
        }

        bool ITnToolsTable.TnUpdateValue(SqlConnection sql_connection, string table_name, string field, string value,string field_key,string value_key)
        {
            string sql = "";
            try
            {
                sql = "UPDATE " + table_name + " SET " + field + "=" + value + " WHERE " + field_key + "=" + value_key + ";";
                SqlCommand cmd = new SqlCommand(sql, sql_connection);
                cmd.ExecuteNonQuery();
                MessageBox.Show(sql);
                return true;
            }
            catch(Exception e)
            {
                MessageBox.Show(e.ToString());
                MessageBox.Show(sql);
                return false;
            }
        }

        #endregion //ITnToolsTable

        
        
        #region ITnToolsSpatialRel Members

        int ITnToolsSpatialRel.TnIntersection(ref IFeatureClass input_feature,ref IFeature intersect_feature,out IFeatureLayer selected_layer,out IFeatureSelection feature_selection,esriSelectionResultEnum type_of_selection)
        {
            int intSelectedFeature = 0;
            //IFeatureCursor featureCursor = intersect_feature.Search(filter_on_intersect_feature, true);
            //lay con tro chi doi tuong cho lop select
            //IFeature selectFeature = featureCursor.NextFeature();

            SpatialFilter spatialFilter = new SpatialFilter();
            
            IFeatureLayer inputLayer = new FeatureLayerClass();
            inputLayer.FeatureClass = input_feature;
            feature_selection =(IFeatureSelection) inputLayer;
            
            IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)inputLayer;

            object obj = Type.Missing;

            //IGeometryCollection geometryCollection = new GeometryBagClass();
            //geometryCollection.AddGeometry(intersect_feature.Shape, ref obj, ref obj);

            spatialFilter.Geometry = intersect_feature.Shape;
            spatialFilter.GeometryField = input_feature.ShapeFieldName;
            spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

            feature_selection.SelectFeatures(spatialFilter, type_of_selection, false);
            selected_layer = flDef.CreateSelectionLayer("newlayer", true, null, null);
            //selectClass = selectLayer.FeatureClass;

            intSelectedFeature = feature_selection.SelectionSet.Count;
            

            return intSelectedFeature;
        }

        int ITnToolsSpatialRel.TnWithin(ref IFeatureClass input_feature, ref IFeature contain_feature, out IFeatureLayer selected_layer, out IFeatureSelection feature_selection, esriSelectionResultEnum type_of_selection)
        {
            int intSelectedFeature = 0;
            //IFeatureCursor featureCursor = intersect_feature.Search(filter_on_intersect_feature, true);
            //lay con tro chi doi tuong cho lop select
            //IFeature selectFeature = featureCursor.NextFeature();

            SpatialFilter spatialFilter = new SpatialFilter();

            IFeatureLayer inputLayer = new FeatureLayerClass();
            inputLayer.FeatureClass = input_feature;
            feature_selection = (IFeatureSelection)inputLayer;

            IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)inputLayer;

            object obj = Type.Missing;

            //IGeometryCollection geometryCollection = new GeometryBagClass();
            //geometryCollection.AddGeometry(intersect_feature.Shape, ref obj, ref obj);

            spatialFilter.Geometry = contain_feature.Shape;
            spatialFilter.GeometryField = input_feature.ShapeFieldName;
            spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;

            feature_selection.SelectFeatures(spatialFilter, type_of_selection, false);
            selected_layer = flDef.CreateSelectionLayer("newlayer", true, null, null);
            //selectClass = selectLayer.FeatureClass;

            intSelectedFeature = feature_selection.SelectionSet.Count;


            return intSelectedFeature;
        }

        #endregion ITnToolsSpatialRel

        #region ITnToolsCalculator Members

        void ITnToolsCalculator.TnAddInfoForThuaMattien(ref IFeatureClass thua, ref IFeatureClass duongBuff05, ref IFeatureClass duongBuff50, string dieukien_locthua, BackgroundWorker bw, esriSelectionResultEnum type)
        {
            //ITnToolsSpatialRel toolSpatialRel = new TnTools();

            // cac doi tuong thua duoc select tu lop thua
            IFeatureSelection featureSelection;
            //layer chua thua mat tien
            IFeatureLayer thuaMattien;
            //cursor chua cac doi tuong duong theo dieu kien nhat dinh
            IFeatureCursor duongBuff05Cur = duongBuff05.Search(null, true);
            //feature ung voi tung duong
            IFeature duongBuff05Feature = duongBuff05Cur.NextFeature();
            //qrf duoc dung de chon cac doi tuong tu featureSelecton
            IQueryFilter qrf = new QueryFilterClass();
            //selectedCur dung de luu ket qua truy van tu qrf
            ICursor selectedCur;
            //row dung de chi tung doi tuong trong selectedCur
            IRow row = null;

            //tim cac thua giao voi tung duong giao thong buffer 0.5m
            //thua duoc chon se duoc:
            //  -gan so mat tien +=1
            //  -gan gia tri don gia ung voi duong mat tien, so sanh voi gia cu, chon gia cao hon
            //  -them vao ghi chu la "mat tien i duong ..."

            int numSelectedFeature = 0;//so luong thua duoc chon ung voi moi duong
            int progress = 0;
            int numOfDuong = 0;

            //List<string[]> listVal = new List<string[]>();
            //listVal = toolTable.TnShowDataUseSQL(sql_connection, "tn_id_huyen", "", 1);

            //khoi tao cac gia tri can thiet
            int somattien = 0; //so mat tien cua thua dat
            float fltDongiaMoi = 0;//don gia moi lay tu duong dang xet
            float fltDongiaCu = 0; //don gia cu lay tu thua duoc chon
            string strGhichu = "";//gia tri lay tu o ghi chu
            string strTenDuong = "";//gia tri ten duong dang xet
            string strMaDuong = "";//gia tri ma duong dang xe
            IFeature thuachon = null;
            IArea area = null;
            float fltGiadat1 = 0;
            //lap cho den khi cac doi tuong duong da duoc su dung het
            while (duongBuff05Feature != null)
            {

                numSelectedFeature = ((ITnToolsSpatialRel)this).TnIntersection(ref thua, ref duongBuff05Feature, out thuaMattien, out featureSelection, esriSelectionResultEnum.esriSelectionResultNew);
                //sau moi lan tim giao
                //  + thuaMattien la layer chua cac thua duoc chon
                //  + featureSelection la bo selection cac thua duoc chon
                //Ta co the su dung 1 trong 2 bien nay de lay cac doi tuong thua duoc chon

                //lay tat ca cac truong
                qrf.SubFields = "*";
                //dieu kien chon thua tu featureSelection
                qrf.WhereClause = "";//"OBJECTID>0";
                //thuc hien truy van de chon thua
                //o day ta can tat ca cac thua trong featureSelection
                //nen dieu kien la ""
                featureSelection.SelectionSet.Search(qrf, false, out selectedCur);
                row = selectedCur.NextRow();
                short a = 0;

                somattien = 0;
                /////////////////////////////////////////////
                //lay cac gia tri tu duong dang xet
                //lay gia tri don gia cua duong dang xet
                fltDongiaMoi = float.Parse(duongBuff05Feature.get_Value(duongBuff05Feature.Fields.FindField("giadat")).ToString());
                //lay gia tri ten duong
                strTenDuong = duongBuff05Feature.get_Value(duongBuff05Feature.Fields.FindField("tenduong")).ToString();
                //lay gia tri ma duong
                strMaDuong = duongBuff05Feature.get_Value(duongBuff05Feature.Fields.FindField("maduong")).ToString();
                //strGhichu la gia tri ghi chu lay tu cot ghi chu
                //ghi chu co dang: <<somattien1>>-<<tenduong1>>-<<dongia1>>,<<somattien2>>-<<tenduong2>>-<<dongia2>>;<<giadat1>>,<<giadat2>>

                //thuc hien vong lap cho cac doi tuong thua duoc chon de gan thong tin
                while (row != null)
                {
                    a++;

                    thuachon = (IFeature)row;
                    area = (IArea)thuachon.Shape;

                    //lay gia tri so mat tien hien tai cua thua dat
                    somattien = int.Parse(row.get_Value(row.Fields.FindField("somattien")).ToString());
                    somattien = somattien + 1;
                    //tang so mat tien len 1
                    row.set_Value(row.Fields.FindField("somattien"), somattien);
                    //gan gia tri [kdat]=30 de xac dinh thua mat tien
                    row.set_Value(row.Fields.FindField("kdat"), "30");
                    //so sanh gia don gia moi voi don gia hien tai
                    //chon don gia cao hon de gan vao cot dongia cua thua chon, khi do gan gia tri ma duong tuong ung vao cot [maduong]
                    fltDongiaCu = float.Parse(row.get_Value(row.Fields.FindField("dongia")).ToString());

                    if (fltDongiaMoi > fltDongiaCu)
                    {
                        row.set_Value(row.Fields.FindField("dongia"), string.Format("{0}", fltDongiaMoi));
                        row.set_Value(row.Fields.FindField("maduong"), string.Format("{0}", strMaDuong));
                    }
                    fltGiadat1 = float.Parse(row.get_Value(row.Fields.FindField("dongia")).ToString()) * float.Parse(Math.Round(area.Area, 1).ToString());
                    row.set_Value(row.Fields.FindField("giadat1"), fltGiadat1);
                    
                    row.set_Value(row.Fields.FindField("dientich1"), Math.Round(area.Area, 1));
                    //lay gia tri ghi chu cu
                    strGhichu = row.get_Value(row.Fields.FindField("ghichu")).ToString();
                    //cap nhat them ghi chu
                    //neu ban dau chua co gia tri ghi chu (duoc fortmat la dau "-") thi ko co dau "," o truoc
                    if (strGhichu != "")
                    {
                        strGhichu += "," + somattien.ToString() + "-" + strTenDuong + "-" + fltDongiaMoi.ToString();
                    }
                    else
                    {
                        strGhichu += somattien.ToString() + "-" + strTenDuong + "-" + fltDongiaMoi.ToString();
                    }

                    //ghi vao ghi chu
                    row.set_Value(row.Fields.FindField("ghichu"), string.Format("{0}", strGhichu));
                    row.Store();
                    row = selectedCur.NextRow();
                }

                //chon doi tuong duong ke tiep cho vong lap
                duongBuff05Feature = duongBuff05Cur.NextFeature();
                progress += 1;
                if (progress > 98)
                {
                    bw.ReportProgress(99);
                }
                else
                {
                    bw.ReportProgress(progress);
                }

            }
        }
        void ITnToolsCalculator.TnCalculateThuaMattientron(ref IFeatureClass thua, ref IFeatureClass duongBuff05, ref IFeatureClass duongBuff50, string dieukien_locthua, BackgroundWorker bw, esriSelectionResultEnum type)
        {
            //ITnToolsSpatialRel toolSpatialRel = new TnTools();
            
            // cac doi tuong thua duoc select tu lop thua
            IFeatureSelection featureSelection;
            //layer chua thua mat tien
            //IFeatureLayer thuaMattien;
            //cursor chua cac doi tuong duong theo dieu kien nhat dinh
            IFeatureCursor duongBuff05Cur = duongBuff05.Search(null, true);
            //feature ung voi tung duong
            IFeature duongBuff05Feature = duongBuff05Cur.NextFeature();
            //qrf duoc dung de chon cac doi tuong tu featureSelecton
            IQueryFilter qrf = new QueryFilterClass();
            //selectedCur dung de luu ket qua truy van tu qrf
            ICursor selectedCur;
            //row dung de chi tung doi tuong trong selectedCur
            IRow row = null;

            //int numSelectedFeature = 0;//so luong thua duoc chon ung voi moi duong
            int progress = 0;
            //int numOfDuong = 0;

            //List<string[]> listVal = new List<string[]>();
            //listVal = toolTable.TnShowDataUseSQL(sql_connection, "tn_id_huyen", "", 1);

            //khoi tao cac gia tri can thiet
            //int somattien = 0; //so mat tien cua thua dat
            //float fltDongiaMoi = 0;//don gia moi lay tu duong dang xet
            //float fltDongiaCu = 0; //don gia cu lay tu thua duoc chon
            //string strGhichu = "";//gia tri lay tu o ghi chu
            //string strTenDuong = "";//gia tri ten duong dang xet
            string strMaDuong = "";//gia tri ma duong dang xe
            
            /////////////////////////////////////////////
            //Tinh gia cho thua mat tien nam trong gioi han 50m (vi tri 1)
            /////////////////////////////////////////////
            //layer chua thua mat tien
            IFeatureLayer thuaMattienTron;
            // cac doi tuong thua duoc select tu lop thua
            //IFeatureSelection featureSelection;
            //cursor chua cac doi tuong duong theo dieu kien nhat dinh
            IFeatureCursor duongBuff50Cur = duongBuff50.Search(null, true);
            //feature ung voi tung duong
            IFeature duongBuff50Feature = duongBuff50Cur.NextFeature();
            //gia tri ma duong cua duong xet
            //strMaDuong
            //doi tuong tinh dien tich
            IArea area;
            IFeature thuachon;//dung de tinh dien tich tu IRow
            float fltGiadat = 0;//gia dat sau cung
            float fltGiadat1 = 0;//gia dat cua phan thua tinh theo gia mat tien
            float fltGiadat2 = 0;//gia dat cua phan thua ko theo gia mat tien
            //so thua duoc chon
            int intWithinFeature;
            while (duongBuff50Feature != null)
            {
                //lay gia tri cua cot [maduong]
                strMaDuong = duongBuff50Feature.get_Value(duongBuff50Feature.Fields.FindField("maduong")).ToString();
                //tim cac thua within trong duong buffer 50m
                intWithinFeature = ((ITnToolsSpatialRel)this).TnWithin(ref thua, ref duongBuff50Feature, out thuaMattienTron, out featureSelection, esriSelectionResultEnum.esriSelectionResultNew);

                //tim cac thua co [maduong] =maduong dang xet
                //lay tat ca cac truong
                qrf.SubFields = "*";
                //dieu kien chon thua tu featureSelection
                qrf.WhereClause = "maduong='" + strMaDuong + "'";//"OBJECTID>0";
                //thuc hien truy van de chon thua
                //o day ta can tat ca cac thua trong featureSelection
                //nen dieu kien la ""
                featureSelection.SelectionSet.Search(qrf, false, out selectedCur);

                row = selectedCur.NextRow();
                //xet tung thua
                while (row != null)
                {
                    thuachon = (IFeature)row;
                    //tinh dien tich cua thua
                    area = (IArea)thuachon.Shape;
                    row.set_Value(row.Fields.FindField("dientich1"), Math.Round(area.Area, 1));
                    //gan gia tri [kdat]=3010 : vi tri 1
                    row.set_Value(row.Fields.FindField("kdat"), "3010");
                    row.set_Value(row.Fields.FindField("vitri"), 1);
                    //lay gia dat 1 da tinh khi tim thua mat tien
                    fltGiadat1 = float.Parse(row.get_Value(row.Fields.FindField("giadat1")).ToString());
                    //row.set_Value(row.Fields.FindField("giadat1"), fltGiadat1);
                    //thua o vi tri 1 nen giadat = giadat1, giadat2=0
                    row.set_Value((row.Fields.FindField("giadat")), fltGiadat1);


                    row.Store();
                    row = selectedCur.NextRow();
                }
                progress += 1;
                if (progress > 98)
                {
                    bw.ReportProgress(99);
                }
                else
                {
                    bw.ReportProgress(progress);
                }
                duongBuff50Feature = duongBuff50Cur.NextFeature();
                
            }
        }
        void ITnToolsCalculator.TnCalculateThuaMattienKotron(ref IFeatureClass thua, ref IFeatureClass duongBuff05, ref IFeatureClass duongBuff50, string dieukien_locthua, BackgroundWorker bw, esriSelectionResultEnum type)
        {
            //ITnToolsSpatialRel toolSpatialRel = new TnTools();
            //ITnToolsWorkspace toolWorkspace = new TnTools();
            // cac doi tuong thua duoc select tu lop thua
            IFeatureSelection featureSelection;
            //layer chua thua mat tien
            IFeatureLayer thuaMattienKotron;
            //cursor chua cac doi tuong duong theo dieu kien nhat dinh
            IFeatureCursor duongBuff05Cur = duongBuff05.Search(null, true);
            //feature ung voi tung duong
            IFeature duongBuff05Feature = duongBuff05Cur.NextFeature();
            //qrf duoc dung de chon cac doi tuong tu featureSelecton
            IQueryFilter qrf = new QueryFilterClass();
            //selectedCur dung de luu ket qua truy van tu qrf
            ICursor selectedCur;
            //row dung de chi tung doi tuong trong selectedCur
            IRow row = null;

            //int numSelectedFeature = 0;//so luong thua duoc chon ung voi moi duong
            int progress = 0;
            //int numOfDuong = 0;

            //List<string[]> listVal = new List<string[]>();
            //listVal = toolTable.TnShowDataUseSQL(sql_connection, "tn_id_huyen", "", 1);

            //khoi tao cac gia tri can thiet
            //int somattien = 0; //so mat tien cua thua dat
            //float fltDongiaMoi = 0;//don gia moi lay tu duong dang xet
            //float fltDongiaCu = 0; //don gia cu lay tu thua duoc chon
            //string strGhichu = "";//gia tri lay tu o ghi chu
            //string strTenDuong = "";//gia tri ten duong dang xet
            string strMaDuong = "";//gia tri ma duong dang xe
            //cursor chua cac doi tuong duong theo dieu kien nhat dinh
            IFeatureCursor duongBuff50Cur = duongBuff50.Search(null, true);
            //feature ung voi tung duong
            IFeature duongBuff50Feature = duongBuff50Cur.NextFeature();
            //gia tri ma duong cua duong xet
            //strMaDuong
            //doi tuong tinh dien tich
            IArea area;
            IFeature thuachon;//dung de tinh dien tich tu IRow
            float fltGiadat = 0;//gia dat sau cung
            float fltGiadat1 = 0;//gia dat cua phan thua tinh theo gia mat tien
            float fltGiadat2 = 0;//gia dat cua phan thua ko theo gia mat tien
            //so thua duoc chon
            int intWithinFeature;

            //tim cac thua co [kdat]=30
            ITnToolsDataManager toolMatnager = new TnTools();
            

            
            ISelectionSet thuavt2 = null;
            IDataset dataset = (IDataset)duongBuff05;
            IWorkspace wsp = dataset.Workspace;
            ITnToolsSpatial toolSpatial = new TnTools();
            

            
            //toolMatnager.IFeatureDataConverter_ConvertFeatureDataset_Example(dataset.Workspace,dataset.Workspace,


            
            //thuavt2 = thua.Select(queryFilter, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionNormal, null);
            duongBuff50Cur = duongBuff50.Search(null, true);
            duongBuff50Feature = duongBuff50Cur.NextFeature();
            
            //int hh = toolMatnager.TnSelectFeaturesByAttribute(ref thua, "kdat='30'",out thuaMattienKotron,out featureSelection, esriSelectionResultEnum.esriSelectionResultNew);
            //MessageBox.Show(hh.ToString());
            IBasicGeoprocessor g = new BasicGeoprocessorClass();
            //thuaMattienKotron.Name = thua.AliasName;
            //MessageBox.Show(thuaMattienKotron.FeatureClass.FeatureCount(null).ToString());
            string out_path;
            string dieukien = "";

            IFeatureClass thuaFcSau50m = null;
            IQueryFilter queryFilter = new QueryFilterClass();
            queryFilter.WhereClause = "kdat='30'";
            IFeatureCursor thuaFcurSau50m=null;
            IFeature thuaFtSau50m=null;

            IFeatureCursor thuaFcurMattien=null;
            IFeature thuaFtMattien=null;
            int j = 0;
            float fltDientich2 = 0;
            float fltDongia=0;
            //int numOfDuongBuff50 = duongBuff05.FeatureCount(null);
            while (duongBuff50Feature != null)
            {
                dieukien="maduong='"+duongBuff50Feature.get_Value(duongBuff50Feature.Fields.FindField("maduong")).ToString()+"'";
                
            //    
                toolMatnager.TnCreateFeatureLayer(duongBuff05.AliasName, "gt_buff_50_lyr", "Database Connections/Connection to ht-laptop.sde",dieukien, out out_path);
                toolSpatial.TnClipInsideSde(ref thua, out_path, "tn_thua_clip", "Database Connections/Connection to ht-laptop.sde");
                thuaFcSau50m = ((ITnToolsWorkspace)this).OpenFeatureClassFromFileMdb("C:\\tayninh\\temp\\tempmdb.mdb", "tn_thua_clip");
                thuaFcurSau50m = thuaFcSau50m.Search(queryFilter, false);
                thuaFtSau50m = thuaFcurSau50m.NextFeature();
                j = 0;
                while (thuaFtSau50m != null)
                {
                    area=(IArea)thuaFtSau50m.Shape;
                    fltDientich2=float.Parse(Math.Round(area.Area,1).ToString());
                    queryFilter.WhereClause = "sothua='" + thuaFtSau50m.get_Value(thuaFtSau50m.Fields.FindField("sothua")).ToString()+"'";
                    thuaFcurMattien=thua.Search(queryFilter,false);
                    thuaFtMattien=thuaFcurMattien.NextFeature();
                    while(thuaFtMattien!=null)
                    {
                        thuaFtMattien.set_Value(thuaFtMattien.Fields.FindField("dientich2"),fltDientich2);
                        fltDongia=float.Parse(thuaFtSau50m.get_Value(thuaFtSau50m.Fields.FindField("dongia")).ToString());
                        fltGiadat2=fltDongia*fltDientich2;
                        fltGiadat1=float.Parse(thuaFtMattien.get_Value(thuaFtMattien.Fields.FindField("giadat1")).ToString());
                        fltGiadat = fltGiadat1 + fltGiadat2;
                        thuaFtMattien.set_Value(thuaFtMattien.Fields.FindField("giadat2"), fltDientich2);
                        thuaFtMattien.set_Value(thuaFtMattien.Fields.FindField("giadat"), fltGiadat);
                        //thuaFtMattien.set_Value(thuaFtMattien.Fields.FindField("ghichu"), "fltGiadat");

                        thuaFtMattien.Store();
                        progress += 1;
                        if (progress > 98)
                        {
                            bw.ReportProgress(99);
                        }
                        else
                        {
                            bw.ReportProgress(progress);
                        }
                        thuaFtMattien = thuaFcurMattien.NextFeature();
                    }
                    progress += 1;
                    if (progress > 98)
                    {
                        bw.ReportProgress(99);
                    }
                    else
                    {
                        bw.ReportProgress(progress);
                    }
                    
                    thuaFtSau50m = thuaFcurSau50m.NextFeature();
                }
                //MessageBox.Show(j.ToString());
                progress += 1;
                if (progress > 98)
                {
                    bw.ReportProgress(99);
                }
                else
                {
                    bw.ReportProgress(progress);
                }
                duongBuff50Feature = duongBuff50Cur.NextFeature();
            }
            
            //intWithinFeature = toolSpatialRel.TnWithin(ref thua, ref duongBuff50Feature, out thuaMattienTron, out featureSelection, esriSelectionResultEnum.esriSelectionResultNew);
            //MessageBox.Show(selectionSet.Count.ToString());
            CopyFeatures copy = new CopyFeatures();
            Geoprocessor gp = new Geoprocessor();
            //IDataset dataset = (IDataset)thua;
            //gp.SetEnvironmentValue("workspace", "Database Connections/Connection to ht_laptop.sde");
            //copy.in_features=featureSelection;
            //copy.out_feature_class = "C:\\";

            //gp.Execute(copy, null);
        }


        void ITnToolsCalculator.TnCalculateThuaMattien(ref IFeatureClass thua,ref IFeatureClass duongBuff05,ref IFeatureClass duongBuff50,string dieukien_locthua, BackgroundWorker bw,esriSelectionResultEnum type)
        {
            //ITnToolsCalculator toolCal = new TnTools();
            //////////////////////////////////////////////////
            //Gan thong tin cho cac thua mat tien
            //toolCal.TnAddInfoForThuaMattien(ref thua,ref duongBuff05,ref duongBuff50, dieukien_locthua, bw, type);
            
            //////////////////////////////////////////////////
            //tinh cho thua mat tien tron thua
            ((ITnToolsCalculator)this).TnCalculateThuaMattientron(ref thua, ref duongBuff05, ref duongBuff50, dieukien_locthua, bw, type);
            
            //////////////////////////////////////////////////
            //gan them thong tin vao cac thua mat tien khong tron thua
            //  - dien tich 1, dien tich 2, 
            ((ITnToolsCalculator)this).TnCalculateThuaMattienKotron(ref thua, ref duongBuff05, ref duongBuff50, dieukien_locthua, bw, type);
            //tinh cho thua mat tien khong tron thua
            
            bw.ReportProgress(100);
            
        }

        void ITnToolsCalculator.TnCalculateAll(string khuvuc,string thua_featureClass, string duong_featureClass, string duong_fc_buff_05, string duong_fc_buff_50, string duong_fc_buff_100, string duong_fc_buff_200, string[,] user_info,string environment, IWorkspaceEdit workspace, BackgroundWorker bw)
        {
            //ITnToolsWorkspace toolWorkspace = new TnTools();
            //ITnToolsSpatialRel toolSpatialRel = new TnTools();
            //ITnToolsSpatial toolSpatial = new TnTools();
            //ITnToolsTable toolTable = new TnTools();
            //ITnToolsCalculator toolCal = new TnTools();
            IFeatureClass duongBuff05 = null;
            IFeatureClass duongBuff50 = null;
            IFeatureClass duongBuff100 = null;
            //format lai cac gia tri cua table
            ((ITnToolsTable)this).TnFormatTable(workspace, thua_featureClass); //Nho go bo cai nay khi chay lan dau

            //mo lop tn_duong_buff_05,tn_duong_buff_50,tn_duong_buff_100 neu ko duoc thi tao moi
            if (((ITnToolsWorkspace)this).CheckLayerExist(user_info, duong_fc_buff_05))
            {
                duongBuff05 = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, duong_fc_buff_05);
            }
            else
            {
                ((ITnToolsSpatial)this).TnBufferInsideSde(duong_featureClass, duong_fc_buff_05, 0.5, environment, workspace);
                duongBuff05 = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, duong_fc_buff_05);
            }
            if (((ITnToolsWorkspace)this).CheckLayerExist(user_info, duong_fc_buff_50))
            {
                duongBuff50 = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, duong_fc_buff_50);
            }
            else
            {
                ((ITnToolsSpatial)this).TnBufferInsideSde(duong_featureClass, duong_fc_buff_50, 50, environment, workspace);
                duongBuff50 = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, duong_fc_buff_50);
            }
            if (((ITnToolsWorkspace)this).CheckLayerExist(user_info, duong_fc_buff_100))
            {
                //MessageBox.Show(toolWorkspace.CheckLayerExist(user_info, duong_fc_buff_100).ToString());
                duongBuff100 = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, duong_fc_buff_100);
            }
            else
            {
                //MessageBox.Show("creat");
                ((ITnToolsSpatial)this).TnBufferInsideSde(duong_featureClass, duong_fc_buff_100, 100, environment, workspace);
                //duongBuff100 = toolWorkspace.OpenFeatureClassFromSDE(workspace, duong_fc_buff_100);
            }


            //mo lop thua
            //IFeatureClass thua = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, thua_featureClass);

            ////////////////////////////////////////
            //tinh cho thua mat tien
            //((ITnToolsCalculator)this).TnCalculateThuaMattien(ref thua, ref duongBuff05,ref duongBuff50, "", bw, esriSelectionResultEnum.esriSelectionResultNew);
            

            ////////////////////////////////////////
            //Tinh cho thua hem
            //IFeatureLayer thuaHem = null;
            //--((ITnToolsCalculator)this).TnAddInfoForHem("tn_hem", "tn_duong", user_info, workspace, environment, bw);

            //Tinh gia dat cho thua hem (thua co so mat tien =0)

        }

        void ITnToolsCalculator.TnAddInfoForHem(string hem_table, string duong_table,string[,] user_info, IWorkspaceEdit workspace,string environment, BackgroundWorker bw)
        {
            //ITnToolsWorkspace toolWorkspace = new TnTools();
            //ITnToolsSpatial toolSpatial = new TnTools();
            //ITnToolsSpatialRel toolSpatialRel = new TnTools();
            //ITnToolsDataManager toolManager = new TnTools();
            IFeatureClass hem_fc = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, hem_table);
            IFeatureClass duong_fc = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, duong_table);
            IFeatureClass duong_fc_buff_1;
            //kiem tra co lop duong buffer 1m chua, neu chua co thi tao moi
            string strNameTableDuongBuffer = duong_table + "_buff_1";
            if(((ITnToolsWorkspace)this).CheckLayerExist(user_info,strNameTableDuongBuffer))
            {
                duong_fc_buff_1 = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, strNameTableDuongBuffer);
            }
            else
            {
                ((ITnToolsSpatial)this).TnBufferInsideSde(duong_table, strNameTableDuongBuffer, 1, environment, workspace);
                duong_fc_buff_1 = ((ITnToolsWorkspace)this).OpenFeatureClassFromSDE(workspace, strNameTableDuongBuffer);
            }
            bw.ReportProgress(50);

            IFeatureSelection featureSelection = null;
            IFeatureLayer selectedLayer = null;

            IFeatureCursor duong_fcu_buff_1 = duong_fc_buff_1.Search(null, true);
            IFeature duong_ft_buff_1 = duong_fcu_buff_1.NextFeature();

            IQueryFilter qrf = new QueryFilterClass();
            ICursor selected_cu = null;
            IRow row = null;
            int intSelectedFeature = 0;
            int progress = 50;
            string maduong="";
            string strCurrentGhichu = "";
            int intDuongchinh = 0;
            ((ITnToolsTable)this).TnFormatColumn(workspace, "tn_hem", "ghichu", "");
            ((ITnToolsTable)this).TnFormatColumn(workspace, "tn_hem", "soduongchinh", 0);
            while (duong_ft_buff_1 != null)
            {
                progress = 0;
                intSelectedFeature = ((ITnToolsSpatialRel)this).TnIntersection(ref hem_fc, ref duong_ft_buff_1, out selectedLayer, out featureSelection, esriSelectionResultEnum.esriSelectionResultNew);

                featureSelection.SelectionSet.Search(null, false,out selected_cu);
                row = selected_cu.NextRow();
                maduong=duong_ft_buff_1.get_Value(duong_ft_buff_1.Fields.FindField("maduong")).ToString();
                while (row != null)
                {
                    intDuongchinh =int.Parse(row.get_Value(row.Fields.FindField("soduongchinh")).ToString());
                    intDuongchinh = intDuongchinh + 1;
                    row.set_Value(row.Fields.FindField("soduongchinh"), intDuongchinh);
                    strCurrentGhichu=row.get_Value(row.Fields.FindField("ghichu")).ToString();
                    if (row.get_Value(row.Fields.FindField("maduong")).ToString() == "")
                    {      
                        row.set_Value(row.Fields.FindField("maduong"), string.Format("{0}", maduong));
                        strCurrentGhichu += intDuongchinh.ToString() + "-" + maduong;
                        row.set_Value(row.Fields.FindField("ghichu"), string.Format("{0}",strCurrentGhichu));
                    }
                    else
                    {
                        row.set_Value(row.Fields.FindField("maduong"), string.Format("{0}", maduong));
                        strCurrentGhichu +=","+ intDuongchinh.ToString() + "-" + maduong;
                        row.set_Value(row.Fields.FindField("ghichu"), string.Format("{0}", strCurrentGhichu));
                    }

                    row.Store();
                    progress += 1;
                    if (progress > 98)
                    {
                        bw.ReportProgress(99);
                    }
                    else
                    {
                        bw.ReportProgress(progress);
                    }
                    row = selected_cu.NextRow();
                }
                progress += 1;
                if (progress > 98)
                {
                    bw.ReportProgress(99);
                }
                else
                {
                    bw.ReportProgress(progress);
                }
                duong_ft_buff_1 = duong_fcu_buff_1.NextFeature();
            }
            bw.ReportProgress(100);

            
        }
        void ITnToolsCalculator.TnAddInfoForThuaHem(ref IFeatureClass thua, ref IFeatureClass hemBuff05, ref IFeatureClass duongBuff100, ref IFeatureClass duongBuff200, string dieukien_locthua, BackgroundWorker bw, esriSelectionResultEnum type)
        {

        }

        void ITnToolsCalculator.TnCalculateThuahem(ref IFeatureClass thua_hem, ref IFeatureClass duongBuff100, ref IFeatureClass duongBuff200, string dieukien_locthua, BackgroundWorker bw, esriSelectionResultEnum type)
        {
            ((ITnToolsCalculator)this).TnCalculateThuahem100(ref thua_hem, ref duongBuff100, dieukien_locthua, bw, esriSelectionResultEnum.esriSelectionResultNew);

            ((ITnToolsCalculator)this).TnCalculateThuahem100_200(ref thua_hem, ref duongBuff200, dieukien_locthua, bw, esriSelectionResultEnum.esriSelectionResultNew);

            ((ITnToolsCalculator)this).TnCalculateThuahem200(ref thua_hem, dieukien_locthua, bw, esriSelectionResultEnum.esriSelectionResultNew);
        }
        //tinh cho thua hem nam cach duong chinh duoi 100m
        void ITnToolsCalculator.TnCalculateThuahem100(ref IFeatureClass thua_hem, ref IFeatureClass duongBuff100, string dieukien_locthua, BackgroundWorker bw, esriSelectionResultEnum type)
        {
            // cac doi tuong thua duoc select tu lop thua
            IFeatureSelection featureSelection;
            //layer chua thua mat tien
            IFeatureLayer thuaMattienKotron;
            //cursor chua cac doi tuong duong theo dieu kien nhat dinh
            IFeatureCursor duongBuff100Cur = duongBuff100.Search(null, true);
            //feature ung voi tung duong
            IFeature duongBuff100Feature = duongBuff100Cur.NextFeature();
            //qrf duoc dung de chon cac doi tuong tu featureSelecton
            IQueryFilter qrf = new QueryFilterClass();
            //selectedCur dung de luu ket qua truy van tu qrf
            ICursor selectedCur;
            //row dung de chi tung doi tuong trong selectedCur
            IRow row = null;

            //int numSelectedFeature = 0;//so luong thua duoc chon ung voi moi duong
            int progress = 0;
            //int numOfDuong = 0;

            //List<string[]> listVal = new List<string[]>();
            //listVal = toolTable.TnShowDataUseSQL(sql_connection, "tn_id_huyen", "", 1);

            //khoi tao cac gia tri can thiet
            //int somattien = 0; //so mat tien cua thua dat
            //float fltDongiaMoi = 0;//don gia moi lay tu duong dang xet
            //float fltDongiaCu = 0; //don gia cu lay tu thua duoc chon
            //string strGhichu = "";//gia tri lay tu o ghi chu
            //string strTenDuong = "";//gia tri ten duong dang xet
            string strMaDuong = "";//gia tri ma duong dang xe
            
            //gia tri ma duong cua duong xet
            //strMaDuong
            //doi tuong tinh dien tich
            IArea area;
            IFeature thuachon;//dung de tinh dien tich tu IRow
            float fltGiadat = 0;//gia dat sau cung
            float fltGiadat1 = 0;//gia dat cua phan thua tinh theo gia mat tien
            float fltGiadat2 = 0;//gia dat cua phan thua ko theo gia mat tien
            //so thua duoc chon
            int intWithinFeature;

            //tim cac thua co [kdat]=30
            //ITnToolsDataManager toolMatnager = new TnTools();
            

            
            ISelectionSet thuavt2 = null;
            IDataset dataset = (IDataset)duongBuff100;
            IWorkspace wsp = dataset.Workspace;
            //ITnToolsSpatial toolSpatial = new TnTools();
            
            //int hh = toolMatnager.TnSelectFeaturesByAttribute(ref thua, "kdat='30'",out thuaMattienKotron,out featureSelection, esriSelectionResultEnum.esriSelectionResultNew);
            //MessageBox.Show(hh.ToString());
            IBasicGeoprocessor g = new BasicGeoprocessorClass();
            //thuaMattienKotron.Name = thua.AliasName;
            //MessageBox.Show(thuaMattienKotron.FeatureClass.FeatureCount(null).ToString());
            string out_path;
            string dieukien = "";

            IFeatureClass thuaFcHem100m = null;
            IQueryFilter queryFilter = new QueryFilterClass();
            queryFilter.WhereClause = "kdat='30'";
            IFeatureCursor thuaFcurHem100m=null;
            IFeature thuaFtHem100m=null;

            IFeatureCursor thuaFcurMattien=null;
            IFeature thuaFtMattien=null;
            int j = 0;
            float fltDientich2 = 0;
            float fltDongia=0;
            //int numOfDuongBuff50 = duongBuff05.FeatureCount(null);
            while (duongBuff100Feature != null)
            {
                dieukien="maduong='"+duongBuff100Feature.get_Value(duongBuff100Feature.Fields.FindField("maduong")).ToString()+"'";
                
            //    
                ((ITnToolsDataManager)this).TnCreateFeatureLayer(duongBuff100.AliasName, "gt_buff_100_lyr", "Database Connections/Connection to ht-laptop.sde",dieukien, out out_path);
                ((ITnToolsSpatial)this).TnClipInsideSde(ref thua_hem, out_path, "tn_thua_clip", "Database Connections/Connection to ht-laptop.sde");
                thuaFcHem100m = ((ITnToolsWorkspace)this).OpenFeatureClassFromFileMdb("C:\\tayninh\\temp\\tempmdb.mdb", "tn_thua_clip");
                thuaFcurHem100m = thuaFcHem100m.Search(queryFilter, false);
                thuaFtHem100m = thuaFcurHem100m.NextFeature();
                j = 0;
                while (thuaFtHem100m != null)
                {
                    area=(IArea)thuaFtHem100m.Shape;
                    fltDientich2=float.Parse(Math.Round(area.Area,1).ToString());
                    queryFilter.WhereClause = "sothua='" + thuaFtHem100m.get_Value(thuaFtHem100m.Fields.FindField("sothua")).ToString()+"'";
                    thuaFcurMattien=thua_hem.Search(queryFilter,false);
                    thuaFtMattien=thuaFcurMattien.NextFeature();
                    while(thuaFtMattien!=null)
                    {
                        thuaFtMattien.set_Value(thuaFtMattien.Fields.FindField("dientich2"),fltDientich2);
                        fltDongia=float.Parse(thuaFtHem100m.get_Value(thuaFtHem100m.Fields.FindField("dongia")).ToString());
                        fltGiadat2=fltDongia*fltDientich2;
                        fltGiadat1=float.Parse(thuaFtMattien.get_Value(thuaFtMattien.Fields.FindField("giadat1")).ToString());
                        fltGiadat = fltGiadat1 + fltGiadat2;
                        thuaFtMattien.set_Value(thuaFtMattien.Fields.FindField("giadat2"), fltDientich2);
                        thuaFtMattien.set_Value(thuaFtMattien.Fields.FindField("giadat"), fltGiadat);
                        //thuaFtMattien.set_Value(thuaFtMattien.Fields.FindField("ghichu"), "fltGiadat");

                        thuaFtMattien.Store();
                        progress += 1;
                        if (progress > 98)
                        {
                            bw.ReportProgress(99);
                        }
                        else
                        {
                            bw.ReportProgress(progress);
                        }
                        thuaFtMattien = thuaFcurMattien.NextFeature();
                    }
                    progress += 1;
                    if (progress > 98)
                    {
                        bw.ReportProgress(99);
                    }
                    else
                    {
                        bw.ReportProgress(progress);
                    }
                    
                    thuaFtHem100m = thuaFcurHem100m.NextFeature();
                }
                //MessageBox.Show(j.ToString());
                progress += 1;
                if (progress > 98)
                {
                    bw.ReportProgress(99);
                }
                else
                {
                    bw.ReportProgress(progress);
                }
                duongBuff100Feature = duongBuff100Cur.NextFeature();
            }
            
        }

        //tinh cho thua hem nam cach duong chinh tu 100m den 200m
        void ITnToolsCalculator.TnCalculateThuahem100_200(ref IFeatureClass thua_hem, ref IFeatureClass duongBuff200, string dieukien_locthua, BackgroundWorker bw, esriSelectionResultEnum type)
        {

        }

        //tinh cho thua hem nam cach duong chinh tren 200m
        void ITnToolsCalculator.TnCalculateThuahem200(ref IFeatureClass thua_hem, string dieukien_locthua, BackgroundWorker bw, esriSelectionResultEnum type)
        {

        }

        #endregion Calculator

        

        #region ITnToolsDataManager Members

        void ITnToolsDataManager.IFeatureDataConverter_ConvertFeatureDataset_Example(IWorkspace sourceWorkspace, IWorkspace targetWorkspace, string nameOfSourceFeatureDataset, string nameOfTargetFeatureDataset,IFields field,IQueryFilter input_query,ISelectionSet input_selectionset)
        {
            //create source workspace name
            IDataset sourceWorkspaceDataset = (IDataset)sourceWorkspace;
            IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName;

            //create source dataset name
            IFeatureDatasetName sourceFeatureDatasetName = new FeatureDatasetNameClass();
            IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureDatasetName;
            sourceDatasetName.WorkspaceName = sourceWorkspaceName;
            sourceDatasetName.Name = nameOfSourceFeatureDataset;
            
            //create target workspace name
            IDataset targetWorkspaceDataset = (IDataset)targetWorkspace;
            IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName;

            //create target dataset name
            IFeatureDatasetName targetFeatureDatasetName = new FeatureDatasetNameClass();
            IDatasetName targetDatasetName = (IDatasetName)targetFeatureDatasetName;
            //IFeatureClassName targetFeatureClassName  = targetDatasetName.Name as IFeatureClassName;
            
            targetDatasetName.WorkspaceName = targetWorkspaceName;
            targetDatasetName.Name = nameOfTargetFeatureDataset;

            //Convert feature dataset
            IFeatureDataConverter2 featureDataConverter2 = new FeatureDataConverterClass();
            //featureDataConverter2.ConvertFeatureClass(sourceFeatureDatasetName, input_query, input_selectionset, targetFeatureDatasetName,targetFeatureClassName,null,field,"",1000,0);
            
            IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
            
            featureDataConverter.ConvertFeatureDataset(sourceFeatureDatasetName, targetFeatureDatasetName, null, "", 1000,0);
            //Console.WriteLine("Conversion Complete");
        }
        int ITnToolsDataManager.TnSelectFeaturesByAttribute(ref IFeatureClass input_feature, string dieukien, out IFeatureLayer selected_layer, out IFeatureSelection feature_selection, esriSelectionResultEnum type_of_selection)
        {
            int intNumOfFeatures = 0;
            IQueryFilter queryFilter = new QueryFilterClass();
            queryFilter.WhereClause = dieukien;

            IFeatureLayer inputLayer = new FeatureLayerClass();
            inputLayer.FeatureClass = input_feature;
            feature_selection = (IFeatureSelection)inputLayer;

            IFeatureLayerDefinition flDef = (IFeatureLayerDefinition)inputLayer;

            feature_selection.SelectFeatures(queryFilter, type_of_selection, false);

            selected_layer = flDef.CreateSelectionLayer("newlayer", true, null, null);
            //selectClass = selectLayer.FeatureClass;

            intNumOfFeatures = feature_selection.SelectionSet.Count;

            return intNumOfFeatures;
        }

        void ITnToolsDataManager.TnCreateFeatureLayer(string in_feature, string out_feature, string environment,string dieukien, out string out_featurelayer_path)
        {
            Geoprocessor GP = new Geoprocessor();
            //MessageBox.Show(dieukien);
            // Intialize the MakeFeatureLayer tool
            GP.SetEnvironmentValue("workspace", environment);
            MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();
            
            makefeaturelayer.in_features = in_feature;
            makefeaturelayer.out_layer = out_feature;
            RunTool(GP, makefeaturelayer, null);

            SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();
            GP.ResetEnvironments();
            SelectByAttribute.in_layer_or_view = out_feature;
            SelectByAttribute.selection_type = "NEW_SELECTION";
            SelectByAttribute.where_clause = dieukien;
            RunTool(GP, SelectByAttribute, null);

           
            CopyFeatures CopyFeatures = new CopyFeatures();

            CopyFeatures.in_features = out_feature;
            CopyFeatures.out_feature_class = @"C:\tayninh\temp\tempmdb.mdb\gt_buff_50";

            // Set the output Coordinate System environment
            //GP.SetEnvironmentValue("outputCoordinateSystem",
            //@"C:\Program Files\ArcGIS\Coordinate Systems\Projected Coordinate Systems\UTM\Nad 1983\NAD 1983 UTM Zone 21N.prj");

            RunTool(GP, CopyFeatures, null);
            out_featurelayer_path = "C:\\tayninh\\temp\\tempmdb.mdb\\gt_buff_50";
        }
        #endregion ITnToolsDataManager
    }
}
